Why does web workers does not give access to DOM object? - javascript

I have been using web-workers in javascript. It would have been an icing on the cake if window, document references were present in web workers context.
I would like to know for what reason was it chosen to not make these references accessible in workers?
Also is there any work-around to use these references?

Standard JavaScript and the DOM API have absolutely no exclusion mechanisms allowing several threads to safely access the same objects.
The solution that is most often chosen to allow multi-tasking in JavaScript is to isolate threads and only let them exchange through messages (or events). Giving access to the DOM to webworkers would break that isolation.
Note that this isn't totally specific to JavaScript: almost all GUI frameworks, whatever the language, restrict the modifications of the GUI to one dedicated thread. JavaScript is more restrictive as most often (always in the browser) you can't share objects at all.
The simple workaround is to let your main thread in the browser do the modifications you need to do, when the background thread gives it the instruction through messages. Or rather: do only the CPU extensive tasks in the webworker, letting the main thread obtain the input data, and update the DOM when the webworker sends the output data.

Related

Is Javascript the only choice for DOM interaction when embedding a web browser?

I've looked at the various ways to embed a web browser into an application (like IE or Safari via OS-specific means, or Firefox/Mozilla via XULRunner, or Chrome via the Chromium Embedded Framework) and I've managed to integrate CEF with my app up to a point where I'm convinced that it'll all work as expected. Now, it seems to me that whenever I want to modify the DOM (e.g. to add or remove elements), I'll have to do this via Javascript, i.e. my application calls out to Javascript where the actual work is done.
I wonder why this is so. My (naive?) belief is that if for example I call appendChild in Javascript, the actual "work" of appending a child will eventually be performed by a C/C++ function as the browser itself is written in C/C++ and not in Javascript. So, I'm wondering why in an embedded web browser I can't call this C/C++ function directly instead of going through Javascript. I understand that for general scripting you don't want other languages than Javascript for security reasons, but if the browser is embedded into an application I can control anyway this shouldn't be the reason, should it?
What am I missing?
CEF is implemented as a layer between chromium's content api and your application. When using CEF, Chromium is a library inside CEF, and you only have access to CEF's Public API, which is more or less restricted to whatever chromium content api leverages (keep in mind no browser was created as an embeddable plugin and then evolved into an application, it was always the other way around). The content API was the way google engineers had to formalize some forms of introspection, but they aren't completed simply because the browser isn't completely modular by itself. There's work in progress on chromium code to separate specific "do-it-all" components in more general ones that you may pick at will.
Therefore you can't simply hook into chromium's implementation details when using CEF: you'd need to patch it to implement something it doesn't expose by itself. CEF implements a class for DOM traversal (see here), but you can only pick at DOM, not change it.
That said, on the C++ side you can do some arbitrary stuff such as inspecting/mangling http requests (which allows you to inject javascript into pages, for instance), and running arbitrary javascript code straight from C++, which can, by it's own turn, asynchronously call back to C++ code by diverse paths (ajax -> http handling in C++, or V8 extensions which you can code straightly in C++.
See https://bitbucket.org/chromiumembedded/cef/wiki/JavaScriptIntegration for more details.
One could customize CEF or go straightly to chromium source code, but that thing is huge. Other solutions I heard of are more or less alike in terms of API limitations, i.e. Awesomium, Mozilla's Gecko, etc.

May a Web Worker render on WebGL-Canvas?

I don't understand how web-workers works... Are web-workers parallel or just preempted?
Is it safe for a web-workers to render to a webgl context?
If I have only a web-worker rendering to webgl context, and my main "thread" is not invoking the worker also, is it safe to the web-worker to render to the webgl context?
When a Web Worker is created, you give it a URI pointing to a JavaScript file. It loads that JavaScript file in a new OS-level thread. You can't control affinity to specific cores or thread priorities, (as of this writing), but the underlying Thread created is real and unfettered. By default, JavaScript running in a Web Worker's thread has NO access to the DOM: you are not given access to the window object nor any DOM-related Classes.
The semantics of the Web Worker thread make it nearly completely unmoored from the default DOM thread. First thing that's interesting is that the Web Worker can run in 100% CPU usage infinite loops without worrying about freezing up the UI. This means the dreaded "Warning: Unresponsive script" message box cannot be triggered by a Web Worker!
The tradeoff of being unmoored is your ability to synchronize and communicate between DOM and worker threads is limited. The explicit conduit between worker and DOM is the postMessage() API for sending data and the onmessage event for receiving events. You can postMessage with strings and objects where your data is cloned from source thread's heap into target thread's heap. onmessage events are only received by your Web Worker when it is idle. This means, in order for onmessage events to be delivered from the DOM to your Web Worker in a timely fashion, the worker must yield frequently; this may put a wrinkle in the way you want to write your code.
It's important to understand that there are a special class of "Transferable Objects" in modern JavaScript implementations where objects that you send to postMessage() are not cloned, but rather ownership of the object is transferred from one thread to another. These are the types of data you want to send to postMessage() whenever possible; any time data is cloned when calling postMessage(), you create TONS of garbage to be GC'd and system performance will suffer.
The collection of Transferable Object types out there has been steadily growing, and the Mozilla Development Network, WhatWG, and W3C are great places to watch the spec research in this area. I couldn't even tell you all of the things that can be Transferred across threads in the browser nowadays, but if I made you a comprehensive list, it'd likely be out of date in a year or less.
Regarding your original question, on Firefox 44+, you can now partially transfer a Canvas to a WebWorker via the HTMLCanvasElement#transferControlToOffscreen function. transferControlToOffscreen creates a Transferable OffscreenCanvas object that you can postMessage over to a Web Worker. On the Web Worker, you can acquire a webgl CanvasContext and issue drawing commands to the canvas from the worker thread without having direct access to the actual canvas tag's DOM that still lives over with the DOM thread.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/transferControlToOffscreen
https://hacks.mozilla.org/2016/01/webgl-off-the-main-thread/
This question has an answer that basically states you can't use webgl from a web worker as web workers don't have access to the DOM and you have to call getContext() on a canvas object to get the webgl context.

Embedding Javascript in Javascript (I'm serious)?

I'm working on a project where players can place graphical objects on a website and animate them with scripts. As the scripts are going to be shared to all participating clients, the scripting environment must be sandboxed, so that users can't ultimately destroy other users experience for all parts of the page.
It is crucial that the scripts can access shared visual content. Therefore I can't isolate them in iframes entirely - besides that I'm wondering if there's a smoother approach to separate contexts.
I have been dabbling with a native version, where I used separate contexts using the V8 javascript engine, but now I want to bring this to the browser - even if it's just Google Chrome only.
Got any ideas?
Sandboxing JavaScript is inherently difficult, chances are that the script will manage to break out no matter how hard you try. A better course of action might be loading the scripts into an iframe without direct access to the main frame and allowing it to communicate with the main frame via window.postMessage(). You could then define an API that the frame is allowed to use this way without being given too much power.
Edit: Same thing is possible with Web Workers as noted in Is It Possible to Sandbox JavaScript Running In the Browser?, browser support for web workers isn't quite as widespread as for window.postMessage() however (compare http://caniuse.com/#search=postMessage and http://caniuse.com/#search=workers).

multi threading using an iframe

I am trying to simulate multi threading using an iframe but I have come across a situation which I do not know if it actually utilizes the iframe process (thread) on its own.
For instance, If I call a method which lays inside an iframe, will it run using the thread created by the iframe or will it run using the main parent window thread?
If it is the latter, then is it possible to change the scope so that the iframe calls the method (so that the program uses a different thread from that of the parent window)
EDIT:
Maybe I should have been more clear on this but I do not want to use WebWorkers simply because I do not have access to the DOM elements.
If you want to run some background tasks just use WebWorkers.
Generally you don't need to multi thread js code. You should use event loops instead.
Take a look at Using web workers from the MDN docs.
The Worker interface spawns real OS-level threads, and concurrency can
cause interesting effects in your code if you aren't careful. However,
in the case of web workers, the carefully controlled communication
points with other threads means that it's actually very hard to cause
concurrency problems. There's no access to non-thread safe components
or the DOM and you have to pass specific data in and out of a thread
through serialized objects. So you have to work really hard to cause
problems in your code.
John Resig wrote Computing with JavaScript Web Workersn back in 2009 on this topic. However, according to When can I use, there is no IE support until IE10 so it may not fit your needs.

Why doesn't Node.js have a native DOM?

When I discovered that Node.js was built using the V8 JavaScript engine, I thought:
Great, web scraping will be easier as the page
will be rendered like in the browser, with a
"native" DOM supporting XPath and any AJAX calls on
the page executed.
Why doesn't it have a native DOM when it uses the same JavaScript engine as Chrome?
Why doesn't it have a mode to run JavaScript in retrieved pages?
What am I not understanding about JavaScript engines vs the engine in a web browser?
Many thanks!
The DOM is the DOM, and the JavaScript implementation is simply a separate entity. The DOM represents a set of facilities that a web browser exposes to the JavaScript environment. There's no requirement however that any particular JavaScript runtime will have any facilities exposed via the global object.
What Node.js is is a stand-alone JavaScript environment completely independent of a web browser. There's no intrinsic link between web browsers and JavaScript; the DOM is not part of the JavaScript language or specification or anything.
I use the old Rhino Java-based JavaScript implementation in my Java-based web server. That environment also has nothing at all to do with any DOM. It's my own application that's responsible for populating the global object with facilities to do what I need it to be able to do, and it's not a DOM.
Note that there are projects like jsdom if you want a virtual DOM in your Node project. Because of its very nature as a server-side platform, a DOM is a facility that Node can do without and still make perfect sense for a wide variety of server applications. That's not to say that a DOM might not be useful to some people, but it's just not in the same category of services as things like process control, I/O, networking, database interop, and so on.
There may be some "official" answer to the question "why?" out there, but it's basically just the business of those who maintain Node (the Node Foundation now). If some intrepid developer out there decides that Node should ship by default with a set of modules to support a virtual DOM, and successfully works and works and makes that happen, then Node will have a DOM.
P.S: When reading this question I was also wondering if V8 (node.js is built on top of this) had a DOM
Why when it uses the same JS engine as Chrome doesn't it have a native
DOM?
But I searched google and found Google's V8 page which recites the following:
JavaScript is most commonly used for client-side scripting in a
browser, being used to manipulate Document Object Model (DOM) objects
for example. The DOM is not, however, typically provided by the
JavaScript engine but instead by a browser. The same is true of
V8—Google Chrome provides the DOM. V8 does however provide all the
data types, operators, objects and functions specified in the ECMA
standard.
node.js uses V8 and not Google Chrome.
Likewise, why doesn't it have a mode to run JS in retrieved pages?
I also think we don't really need it that bad. Ryan Dahl created node.js as one man (single programmer). Maybe now he (his team) will develop this, but I was already extremely amazed by the amount of code he produced (crazy). He wanted to make a non-blocking easy/efficient library, which I think he did a mighty good job at.
But then again, another developer created a module which is pretty good and actively developed (today) at https://github.com/tmpvar/jsdom.
What am I not understanding about Javascript engines vs the engine in
a web browser? :)
Those are different things as is hopefully clear from the quote above.
The Document Object Model (DOM in short) is a programming interface for HTML and XML documents and it represents the page so that programs can change the document structure, style, and content. More on this subject.
The necessary distinction between client-side (browser) and server-side (Node.js) and their main goals:
Client-side: accessing and displaying information of the web
Server-side: providing stable and reliable ways to deliver web information
Why is there no DOM in Node.js be default?
By default, Node.js doesn't have access, nor have any knowledge about the actual DOM in your own browser. Node.js just delivers the data, that will be used by your own browser to process and render the whole website, the DOM included. The server provides the data to your browser to use and process. That is the intended way.
Why wouldn't you want to access the DOM in Node.js?
Accessing your browser's actual DOM using Node.js would be just simply out of the goal of the server. Your own browser's role is to display the data coming from the server. However it is certainly possible and there are multiple solutions in different level of depths and varieties to pre-render, manipulate or change the DOM using AJAX calls. We'll see what future trends will bring.
Why would you want to access the DOM in Node.js?
By default, you shouldn't access your own, actual DOM (at least some data of it) using Node.js. Client-side and server-side are separated in terms of role, functionality, and responsibility based on years of experience and knowledge. Although there are several situations, where there are solid reasons to do so:
Gathering usage data (A/B testing, UI/UX efficiency and feedback)
Headless testing (Development, automation, web-scraping)
How can you access the DOM in Node.js?
jsdom: pure-JavaScript implementation, good for testing your own DOM/browser-related project
cheerio: great solution if you like/often use jQuery
puppeteer: Google's own way to provide headless testing using Google Chrome
own solution (your possible future project link here)
Although these solutions do not provide a way to access your browser's own, actual DOM by default, but you can create a project to send some form of data about your DOM to the server, then use/render/manipulate that data based on your needs.
...and yes, web-scraping and web development in terms of tools and utilities became more sophisticated and certainly easier in several fields.
node.js chose not to include it in their standard library. For any functionality, there is an inevitable tradeoff between comprehensiveness, scalability, and maintainability.
That doesn't mean it's not potentially useful. There is at least one JavaScript DOM implementation intended for NodeJS (among other CommonJS implementations).
You seem to have a flawed assumption that V8 and the DOM are inextricably related, that's not the case. The DOM is actually handled by Webkit, V8 doesn't handle the DOM, it handles Javascript calls to the DOM. Don't let this discourage you, Node.js has carved out a significant niche in the realtime server market, but don't let anybody tell you it's just for servers. Node makes it possible to build almost anything with JavaScript.
It is possible to do what you're talking about. For example there is the very good jsdom library if you really need access to the DOM, and node-htmlparser, there are also some really good scraping libraries that take advantage of these like apricot.
2018 answer: mainly for historical reasons, but this may change in future.
Historically, very little DOM manipulation was done on the server. Addiotinally, as other answers allude, the JS stdlib and the DOM are seperate libraries - if you're using node, for, say, Unix scripting, then HTMLElement and NodeList etc aren't really relevant to that.
However: server-side DOM manipulation is now a very common part of delivering web apps. Web servers need to understand the structure of pages, and, if asked to render a resource as HTML, deliver HTML content that reflects the initial state of a web application. This means web apps load much faster than if the server simply delivers a stub page and has the browsers then do the work of filling in the real content. Currently this is done with JSDom and similar, but in the same way node has Request and Response objects built in, having DOM functions maintained as part of the stdlib would help with this task.
Javascript != browser. Javascript as a language is not tied to browsers; node.js is simply an implementation of Javascript that is intended for servers, not browsers. Hence no DOM.
If you read DOM as 'linked objects immediately accessible from my script' then the answer 'it does, but it's very different from set of objects available from web document script'. The main reason is that node is 'evented I/O for V8', not 'HTML tree objects for V8'
Node is a runtime environment, it does not render a DOM like a browser.
Because there isn't a DOM. DOM stands for Document Object Model. There is no document in Node, so not DOM to manipulate it. That is definitively a browser thing.
You can use a library like cheerio though which gives you some simple DOM manipulation.
Node is server-level JavaScript. It's just the language applied to a basic system API, more like C++ or Java.
It seems people have answered 'why' but not how. A quick answer of how is that in a web browser, a document object is exposed (hence DOM , document object model). On windows this object is called document object. You can refer to this page and look at the methods it exposes which are for handling HTML documents like createElement. I don't use node.js or haven't done COM programming in a while but I'd imagine you could use DOM in node.js by simply calling the COM object IHTMLDocument3. Of course for other platforms like Mac OS X or Linux you would probably have to use something from their OS api. This should allow you to easily build a webpage server side using DOM, or to scrape incoming web pages.
Node.js is for serverside programming. There is no DOM to be rendered in the server.
1) What does it mean for it to have a D ocument O bject M odel? There's no document to represent.
2) You're most of the time you're not retrieving pages. You can, but most Node apps probably won't be.
3) Without a document and a browser, Javascript is just another programming language. So you may ask why there isn't a DOM in C# or Java

Categories

Resources