Can a Native Client module render HTML generated by C++ code? - javascript

I have some data analysis code that processes an input file and outputs HTML and/or SVG. It is C++ and CPU-intensive.
I would like to create a browser plugin so that my code can be used without leaving the browser. Google's Native Client framework and the Pepper API sound interesting but perhaps is a little too restrictive. From a Native Client module is it possible to do the following via Pepper?
Access a local file on the users filesystem. I know NaCl sandbox
generally prevents this but there is surely a way to pass a
user-selected file from the Javascript layer down into NaCL?
Output HTML or SVG back to the browser. Is there any way that the C++ can modify the containing document's DOM?

i am less certain for (1), but (2) is definitely not directly possible.
for (1), the Pepper API is supposed to allow file pickers to make files available to NaCl modules, the same way that WebFS allows it for JavaScript. i'm not sure of the implementation status of this.
for (2), C++ code cannot directly manipulate the DOM. however, the NaCl module can use the PostMessage interface to send strings to JavaScript code, which can then do the actual DOM manipulation. note that in Chrome, NaCl modules are event handlers. this means that if the computation is started by some event and run synchronously (and it is CPU intensive), it would cause the browser to lose interactive responsiveness, or to become janky, since the event handler would take too long to return. a better way is to spawn a background thread to do the work in the event handler (or wake a worker thread up), and return from the event handler immediately. when the computation is done and results are ready, PostMessage the result back to let the JavaScript thread wake up (again as an event handler) and do the DOM manipulation. note that currently PostMessage must be invoked on the main thread, so the worker thread must use CallOnMainThread to wake up the main event handler thread so that it can in turn do the PostMessage.
isn't continuation passing style fun?

A file can be uploaded to the HTML file system using a file input element and JavaScript, where it can then be manipulated by both JavaScript and NaCl. The nacl_io library implements standard posix methods such as fread, so once you've saved your file it's pretty straight forward. See here for JS (don't be put off by the deprecation message, it's implemented in Chrome), and here for NaCl.
As #Bennet Yee mentioned, the NaCl module can not modify the page, but instead passes messages back to the browser window which are handled by your JavaScript. Sounds like you'll probably want to pass back some JSON data. See here for Google's docs on the messaging system.

Related

How do I 'getElementById' from a module in JavaScript? [duplicate]

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

Preventing a specific function in a specific script from executing inside a browser

Is it possible to prevent a specific function in a specific script from executing inside a browser, possibly by redirecting calls of that function to a static/modified version of the script file with a predefined rule? (Similar to how we use an adblocker extension or userscript to customize the DOM, but this time to manipulate the scripts themselves.)
Consider this scenario, website.com utilizes client-side rendering heavily. When https://website.com/article.html is visited, the bundled big JS file https://website.com/entire-app.js will render the entire webpage, both contents and ads.
In the end, a function named isAdblockerFound() in https://website.com/entire-app.js will be called by antiAdBlockerMethod() in the same script file. It checks if ads on the page are indeed loaded and performs other adblocker detection procedures. If this function returns true, antiAdBlockerMethod() will then trash and replace all the rendered elements in the DOM with some big warning text.
In this situation, the script https://website.com/entire-app.js handles all the client-side page rendering, both ads and contents, so simply blocking it from loading will render the website unaccessible.
In order to only bypass/fool the isAdblockerFound(), the idea I came up with is to somehow replace the isAdblockerFound() function with a function which always returns false, before it is called. That is, to tell the browser to redirect calls of isAdblockerFound() to a customized isAdblockerFound() in a static/modified version of the script file, hosted locally or resides temporarily in the browser.
I understand that if we don't need a predefined rule, we can use the devtools to freeze the script with a breakpoint and execute anything between lines easily. But how can we do this automatically with a predefined rule? What extensions/tools are needed?
Google didn't give me anything useful (all the results are about routing in express etc).
EDIT: I understand that I can disable my adblocker anytime and that would be a trivial solution for this question. I also understand why ads exist on the web in the first place, and appreciate the valuable contents made possible by ads. Actually I have never had motive to apply this to any websites I visit, and I am not aware of any websites employing adblocker checking procedures exactly like website.com in my example. I asked this question because I was simply curious if it is possible to bypass this kind of checking.
I suppose, in a different context, one website could be malicious and a security engineer would need to perform an analysis. He might find fooling an environment checking procedure useful in that scenario.
Firefox provides the webextension API webRequest.filterResponseData() to inspect and rewrite the content of any network request, including javascript loads. This would allow you to parse the javascript and replace the method in question.
That only leaves the task of building a robust, streaming javascript matching and rewriting engine.

What's universal javascript?

I've been reading articles online about what universal javascript is but I'm still not comfortable with the definitions each site is giving which is, "code that can run on the client and server." Does this mean that a node.js app is inherently universal javascript because it will have javascript running in the client side and server side. Or does universal javascript have to do with server side rendering then client side rendering?
Preface: I cannot find any highly-authoritative (e.g. ECMA, Microsoft, Mozilla or Google) source that provides a strict definition of "universal JavaScript" or "isomorphic JavaScript" - at most I've found a few blog posts (albeit by influential personalities) however I can see why a newcomer might be confused.
It seems there are two definitions going around which are similar, but with crucial differences:
1. To refer to JavaScript which runs anywhere
This definition refers to JavaScript which does not take a dependency on any specific client-side or server-side API, instead they only make use of features present in JavaScript's built-in library (String, Array, Date, function, Math etc) or on other libraries that also similarly restrict their dependencies (a transitive relation).
Remember that "JavaScript" does not mean that the DOM API, AJAX, HTML5 <canvas> (and so on) are available - it just means the JavaScript scripting language is being used - that's it. JavaScript has been available outside of web-browsers for over 20 years now (Windows support JavaScript as a shell-scripting language in cscript.exe/wscript.exe and ASP 3.0 supported server-side JScript as an alternative to VBScript - and the .NET Framework has "JScript.NET" too).
So in this case, if you wrote a library that adds some useful string functions, which only references String, then that script would work without issue in a Node.js server environment or an in-browser environment.
But if your script ever used the window object (only present in browsers) or express (a library only for Node) then it loses "universal" status because it cannot "run everywhere".
2. To refer to JavaScript which renders the same HTML whether on the server or on the client
e.g. http://isomorphic.net/
This definition is actually a strict subset of the first definition: as the same script must (by definition) run inside both a server/Node.js context, but also a browser DOM context - and when it runs it generates content (typically HTML) that is then displayed in the user's browser (and by doing this it must take a dependency on both a Node API and the W3C DOM - so then it cannot strictly run "anywhere" because neither are available in a cscript.exe environment, for example.
Note: There is debate if use of XMLHttpRequest or fetch makes a script universal or not - as their presence is not guaranteed (as technically they're part of the DOM, not JavaScript's built-in library).
In this 2015 blog post ( https://medium.com/#ghengeveld/isomorphism-vs-universal-javascript-4b47fb481beb ) the author argues that only the term "isomorphic JavaScript" should be used to refer to rendering code that runs in both browser and server environments, while "universal JavaScript" should refer to truly portable, environment-agnostic, JavaScript (i.e. my first definition).
Nowadays Single Page Applications have become very popular but they have problems, SEO, for example.
So, how does an SPA work? JavaScript loads in the browser and loads data from an API. Most of the rendering is done on the client Side. But search engine bots have a hard time indexing the page because it doesn't have much without JS.
Now, Universal/Isomorphic App comes to the rescue. At the initial page load, the original page renders on the server. After that, the app works like an SPA. It's got better SEO because when a search engine bot asks for a page, the server returns the whole rendered HTML page, with content and meta tags.
Edit
An isomorphic app can be done with JavaScript (Node.js), PHP or some other language, but if that app written with Node.js, then we can call it universal as both the backend and frontend are in JavaScript.
I'll try to explain it with examples, even if other answers seem already accurate.
A basic example
Imagine you develop a SPA that render an Hello World message. This means that your browser loads an HTML file with a <script> tag (or the reference to a JS file) that actually makes this happen. You can prove that "Hello world" is generated by JavaScript in the client browser, because if you deactivate JavaScript you won't see any message.
Now isolate the code that prints the string "Hello World", it doesn't need much to be adapted and work in the server side. In fact, the server just needs to send an HTML string that "contains" the <h1>Hello World</h1> inside its body.
So what it makes it universal/isomorphic? The fact that the code can understand in which environment it runs (the browser, the server or possibly an other environment) and it keeps functioning. Remember: code usually only runs in one of the two environments, the thing is that you wrote some common code that can run in both environments (universal).
The behavior of a more complex Universal App
Imagine that you struggle to develop a new Universal website. The code can acknowledge in which environment it is running and work just fine. So you have, let's say, 80% of your code that is shared, it doesn't even need to know the environment, and the rest of your code is there to managing the fact that your app can be used in the client or in the server.
How does this work?
The client first contacts the server that returns some HTML to the client with all the content of the page, elaborated in the server. So the server renders the application. In the mean time the browser downloads the script file where your single page can work in the client. The client is now rendering the same page again. You won't see anything, because if it is properly done, it will just be the same (of course all the animations and real time features have to work client-side, so you will eventually see your animations starting)
When the user clicks an internal link or uses an interactive feature, or eventually fills out and submits a form, the client-side code is in use. The server doesn't get any request, especially assuming that all the interaction are abstracted in an API that is not our isomorphic app.
If the user goes crazy and wants to deactivate JavaScript, how do you assure that, for example, forms still work? Here is a trick you can use:
<form
method="post"
action="/api/fakeBackendRoute"
onSubmit={this.handleSubmit}
>
[input fields here]
</form>
When the client JS is available, the handleSubmit is executed and the propagation of the event is prevented. This way the server side code will never fire.
If the client JS is disabled, then handleSubmit will never be executed and you have to care that your /api/fakeBackendRoute will handle the data exactly how the client would.
Why do people use it?
In my opinion the difficulty of undertaking the development of an Universal App is often underestimated. Good reasons to use it are:
Be more SEO friendly
Support very old browsers. For example, if you want to support IE8, you could do something like this:
<!--[if gt IE 8]><!-->
<script src="yourfile.js"></script>
<!--<![endif]-->
Be more accessible for people that don't want to use JavaScript
Other reasons could be:
Performance, if it matters to your application. You can improve your response time by using, for example, a lot of Node capabilities to stream your HTML string in the first request, and eventually later be more in the client, where things will be likely faster. But you could decide whether it is faster to render on the client or on the server, depending on the content and how you create your assets.
If someone knows other good reasons, just comment below and I will add them.
Some good reference links:
https://medium.com/airbnb-engineering/isomorphic-javascript-the-future-of-web-apps-10882b7a2ebc
https://medium.com/front-end-developers/handcrafting-an-isomorphic-redux-application-with-love-40ada4468af4
https://github.com/xgrommx/awesome-redux

CSS Selection inside Web Workers?

I want to extract data from an HTML string in a Web Worker.
I want to clarify that I do not want to manipulate the DOM. I am sending an HTML string to the Web Worker, which then should extract data from the HTML, and then return the extracted data.
In the browser I could do:
var html = $("<body><div>...more html...</div></body>");
var extractedText = $(".selector", html).text();
My Question:
What is the equivalent of the above code in a Web Worker environment if given the same HTML string? There's no jQuery, no DOMParser, no querySelector.. in the Web Worker etc. Are there alternatives?
The Why:
I'm doing on the fly scraping of pages in a browser and don't want to block the UI thread because it's pretty heavy work.
I've looked at jsdom, cheerio, etc. but could not figure out how to make them work.
Regarding suggested duplicates:
I have reviewed both of the suggested duplicates and they are ones that I have read before while searching for answers to this question. They address XML parsing and not HTML parsing, and also do not address how to use CSS-selection inside Web Workers.
Short answer:
You cannot do any sort of HTML/CSS manipulation, including querying, in a web worker.
Long answer:
There are many DOMs. There's the main DOM, which is rendered on the page, but everything that a browser does that touches an HTML or XML tree, including querySelector and friends, requires the browser to build a DOM for that tree. (see also: DocumentFragment)
One of Mozilla's developers talked a bit about some reasons why they can't build any DOMs on worker threads (found via this question, on nabble):
You're assuming that none of the DOM implementation code uses any sort of non-DOM objects, ever, or that if it does those objects are fully threadsafe. That's just not not the case, at least in Gecko.
The issue in this case is not the same DOM object being touched on multiple threads. The issue is two DOM objects on different threads both touching some global third object.
For example, the XML parser has to do some things that in Gecko can only be done on the main thread (DTD loading, offhand; there are a few others that I've seen before but don't recall offhand).
So. We obviously can't use querySelector, createElement, or anything useful in a worker, so what can we do?
Build our own DOM parser/selector modules, of course!
Not really. Try including a copy of htmlparser2 in your worker, maybe via browserify (making that work is its own question). With that, and with CSSselect to allow querySelector-like selecting, you should be ready to go.
Admittedly, you can't use jQuery with those, but for simple querying needs they (and querySelector/querySelectorAll) should be more than sufficient.
You can make dom selection inside worker but you will need to create an API that will use post message to change data between main tread and worker (because you can't use DOM directly in worker). The limitation is that you will need to pass strings between, so you can't return Dom Nodes, unless you have some code that will create DOM nodes in worker based on data from main tread.
Because JavaScript is dynamic it should be easy to create dynamic wrapper that will create all those functions for you, and will allow to call querySelelector('.foo') and expose all the Dom APIs. With proxy objects you can even allow to use querySelelector('.foo').innerHTML = 'hello'; in worker with proper code.
There is library that make creating such API easier Comlink from Google. If you don't want to use library you can check this code, this git web terminal that expose isomorphic git functions using RPC like code to worker (It's inspired by Jason's Miller
workerize).
Create worker:
https://github.com/jcubic/git/blob/gh-pages/js/main.js#L116
Worker code
https://github.com/jcubic/git/blob/gh-pages/js/git-worker.js
and quick search give this project that looks promising "Worker DOM", it should give you DOM api in worker (that I'm almost sure use solution I proposed) but I didn't check it and I'm not sure how it works.
With some bit of work you may even have working jQuery inside worker, it would good project to make open source.

how to automate drag and drop of files into a headless browser's window?

I'm building a web application which involves drag'n'dropping of files from user's system into browser's window.
I want to automate the user's interaction with the UI using one of the headless browsers available (for the purpose of test driven development) so the virtual DOM gets files drop event.
I spent two hours looking for the out-of-the-box solution without any success.
The only thing that can be automated is uploading a single file with input[type=file].
That's not what I want.
Is there any ready to use solution for Mac OS X or Linux?
I know no good solution but I have a couple of workarounds:
You can run the browser in a VM or Xnest or VNC server on Linux. That gives you a UI. Protocols like VNC also allow you to emulate the mouse, so you can open a file browser and really drag a file over.
Pro: Does the real thing.
Con: Brittle. Lots of work to set up.
What exactly are you testing? The file upload component in the browser? Or processing the files on the server?
If you're using an existing / boxed component for multi file upload, then why are you testing it? Don't the people who wrote it for you test? Why replicate this effort?
If you're only interested whether the server processes the files correctly, use a HTTP client library to manually upload. Use a HTTP proxy like Charles to see what happens between the real client and the server if necessary.
If you want to test the interaction of your app and the widget, things get tricky. To test this, you need to enable logging/debugging in your browser to see which events are being triggered during the drop. JavaScript allows you to create any event. For phantomjs, try --webdriver-loglevel=DEBUG
When you know how the "drop" event looks like, create an artificial one and send it to the widget.
[EDIT] If you write your own file upload widget, then I suggest to log the "drop" event to the console. With many modern browsers, you will get an active element in the console that you can examine. Use this to find out which objects are used and what value is in each slot.
That should give you enough information to create such an event from a test case. I suggest to use jQuery during the tests since it has a nice framework to build events from scratch.

Categories