I want to create a class called NMLDocument which inherits from Document but has some additional properties.
I've tried this code:
NMLDocument.prototype = Object.create(Document.prototype);
But the browser throws the following error:
Ignoring get or set of property that has [LenientThis] because the "this" object is incorrect.
Is there any way around? (I don't want to include all the properties separately)
What you try to achieve probably isn't possible since internal types like Document don't have to behave like normal JS objects (usually, Document won't because of security reasons).
If you want to simulate a browser, you can try envjs which is a pretty complete implementation of a browser in pure JavaScript.
If you need a real browser, try phantomjs. That's a WebKit-based browser which is controlled by JavaScript or CoffeeScript. It offers many nice APIs on the controlling side (like listeners for resource loading).
If you want to use XULRunner, try to write a wrapper or overwrite specific parts of Document.
Related
JavaScript lets you add arbitrary properties and methods to any object, including DOM nodes. Assuming the property was well namespaced (something like _myLib_propertyName) so that it would be unlikely to create a conflict, are there any good reasons not to stash data in DOM nodes?
Are there any good use cases for doing so?
I imagine doing this frequently could contribute to a sloppy coding style or code that is confusing or counter-intuitive, but it seems like there would also be times when tucking "custom" properties into DOM nodes would be an effective and expedient technique.
No, it is usually a bad idea to store your own properties on DOM nodes.
DOM nodes are host objects and host objects can do what they like. Specifically, there is no requirement in the ECMAScript spec for host objects to allow this kind of extension, so browsers are not obliged to allow it. In particular, new browsers may choose not to, and existing code relying on it will break.
Not all host objects in existing browsers allow it. For example, text nodes and all ActiveX objects (such as XMLHttpRequest and XMLDOM objects, used for parsing XML) in IE do not, and failure behaviour varies from throwing errors to silent failure.
In IE, the ability to add properties can be switched off for a whole document, including all nodes within the document, with the line document.expando = false;. Thus if any of the code in your page includes this line, all code relying on adding properties to DOM nodes will fail.
I think more than anything, the best reason not to store data in the DOM is because the DOM is meant to represent content structure and styling for an HTML page. While you could surely add data to the nodes in a well-namespaced manner as to avoid conflicts, you're introducing data state into the visual representation.
I'm trying to find an example for or against storing data in the DOM, and scratching my head to find a convincing case. In the past, I've found that the separation of the data state from the visual state has saved headache during re-designs of sites I've worked on.
If you look at HTML 5 there is the data attribute for fields that will allow you to store information for the field.
Don't be surprised to run into trouble with IE 6 & 7. They are very inconsistent with setAttribute vs set as a property.
And if you're not careful you could set circular references and give yourself a memory leak.
http://www.ibm.com/developerworks/web/library/wa-memleak/
I always set node properties as a last resort, and when I do I'm extra careful with my code and test more heavily than usual.
For what it's worth, the D3.js library makes extensive use of custom properties on DOM nodes. In particular for the following packages that introduce interaction behaviors:
https://github.com/d3/d3-zoom - the __zoom property
https://github.com/d3/d3-brush - the __brush property
D3 also provides a mechanism for putting your own custom properties on DOM elements called d3.local. The point of that utility is to generate property names that are guaranteed not to conflict with the DOM API.
The primary risk I can see associated with custom properties on DOM nodes is accidentally picking a name that already has some meaning in the DOM API. If you use d3.local or maybe prefix everything with __, that should avoid conflicts.
Web App Model
Suppose I have a sensitive JS object by which I can do critical stuff. My requirement is that I would like to wrap this object entirely such that no one can access it. Here is my pattern to wrap this object.
var proxy = (function (window){
// A private reference to my critical object (i.e. big apple)
var bigApple = window.bigApple;
// Delete this property so that no one else can access it
delete window.bigApple;
// Oooah, It's mine! I'm now eating it :)
// Public APIs exposed globally
return {
doStuffWithBigApple: function (){
// The Script element being executed now
var who = document.currentScript;
// Access control
if(isLegitimate(who)){
return bigApple.doStuff();
}
}
};
}) (window);
By this code I export a public literal object named proxy so that every one can access it.
What is that isLegitimate? It is an abstract function to be implemented which decides which script elements access to which methods of my big apple. The decision is made with regard to src attribute of the script element. (i.e. their domain)
Others use this public API like this:
proxy.doStuffWithBigApple();
Attack Model
In my web app there are placeholders for advertising such that external contents including JavaScript codes could be loaded and get executed. All of these external resources eagerly would want to access my big apple.
Note: Those are added after my scripts resulting in there is no access to the original window.bigApple.
My Question
Is there any circumventing way for my security model?
Critical edges:
Changing src attribute at parse-time. --- Not possible, because src can only be set once.
Adding script element at run-time --- No problem is raised
Your idea of creating a proxy is good imo, however, if you have access to ES6, why not looking into Proxy? I think it does what you want out-of-the-box.
The MDN provides good examples on how do traps for value validation in a setter, etc.
EDIT :
Possible trap I have imagined :
document.currentScript is not supported in IE. So if you care about it and decide to polyfill it/use a pre-exisiting polyfill, make sure it is secure. Or it could be used to modify on the fly the external script url returned by document.currentScript and skew the proxy. I don't know if this could happen in real life tho.
This way for protecting JavaScript objects has a very significant issue which should be addressed, otherwise this way will not work properly.
MDN noted on this API that:
It's important to note that this will not reference the <script> element if the code in the script is being called as a callback or event handler; it will only reference the element while it's initially being processed.
Thus, any call to proxy.doStuffWithBigApple(); inside callbacks and event handlers might lead to misbehaving of your framework.
this is maybe a stupid question, but when I search for an answer I get jQuery results that talk about object arrays. I'm not there yet and want to understand how javascript itself is interacting with the DOM.
The DOM is an object tree created and used to render HTML if I'm not mistaken? And javascript has objects of the same name. For example: window, document, and elements with id... Are these the same objects?
I've read that javascript is part of HTML5, is this because the javascript objects are in fact the DOM objects and that the javascript language has been built up around the DOM? If so, how could it ever be possible to use javascript without the DOM? - For example, how could you ever make a desktop app? I use a program called brackets which is coded in javascript.
I think MDN has a great definition:
The Document Object Model (DOM) is an API for manipulating HTML and XML documents. It provides a structural representation of the document, enabling you to modify its content and visual presentation by using a scripting language such as JavaScript.
So the DOM is the specification of an API which can be used to select, manipulate and create new elements in a webpage, via an API.
That API is made visible (or exposed) to us, JavaScript developers, by allowing us to access JavaScript objects which implement particular parts of the DOM API.
The window element is one of those; as MDN says
The window object implements the Window interface, which in turn inherits from the AbstractView interface.
window is the JavaScript object window.
... it implements the DOM Window interface
... which, behind the scenes (we don't really care about this) inherits the AbstractView interface.
However, as well as implementing the DOM Window interface, window also exposes several JavaScript types and functions; which are not part of the Window interface, but exist on the window object.
All the types; window.String, window.Object, window.Array.
Math
...
As you specifically mentioned document; document is part of DOM Window interface, which you can see listed here.
In short, anything which involves selecting, manipulating and creating HTML elements will usually be part of the DOM.
HTML5 is the latest HTML standard which add new HTML elements such as <audio> and <video> tags. The DOM API has been updated to allow those new elements to be controlled by the API.
In turn, the JavaScript objects which implement those API's have to be updated.
JavaScript is a programming language. The DOM can be thought of as a framework or library which lets you control HTML from JavaScript.
JavaScript can be used completely standalone, without this library; which is exactly what happens in environments such as NodeJS and Brackets.
Take it this way:
You need an environment and a program.
The environment is the browser
The program has :
an interface( web page aka document)
code (javascript)
So you end up with 3 object models
DOM document object model
BOM browser object model
JOM javascript object model
The following graph may help:
http://javascript.info/tutorial/browser-environment
For a Greasemonkey script running on twitter.com, I need to access the twttr.streams.TweetStream instance of the main timeline (dubbed 'Home' internally) programmatically. I'm using Firebug and Javascript Deminifier to bring their JS code into a readable form. That way, I could previously work out that I could access it via twttr.app.currentPage().streamManager.streams.current in my GM script.
This has worked perfectly over the last months. Today, Twitter seems to have changed their code, breaking my approach (not their fault, obviously ;)).
I can still get to the current page via twttr.app.currentPage(). However, it doesn't have a streamManager field anymore.
I've tried various paths to get there, but all were dead ends. Unfortunately, I don't completely understand the class system they are using yet. It seems like the streamManager property is still there -- on a mixin called mixins/streamablePage, which should be provided by the class twttr.components.pages.Home. I can't figure out how to access it, though. (Or if the class system hides it in some impenetrable way.) That mixin also provides a getStreamManager() method, but I can't access that either, e.g. via twttr.app.currentPage().getStreamManager(). Is there any trick I need to perform to get access to these mixins from the outside?
Can anyone spot an alternative method to get to this instance? Note that I need the original instance used on the timeline page. Yes, I could easily create a new instance via new twttr.streams.TweetStream(), but I'm trying to hook into the original events.
I am perfectly aware that this use case is as unsupported as it gets, that's why I'm asking you, not them. :) For the record, I'm not attempting to do anything evil, just providing additional functionality for myself.
Until they change it again, twttr.app.currentPage()._instance.getStreamManager()
I'd like to dynamically change some of the standard JS DOM objects from within a web browser.
For instance, when I execute:
var site = location;
I want to specify a new value for my browser's "window.location" object other than the "correct" one (the URL used to access the requested page) at run time, either through a debugger-like interface or even programmatically if need be.
Although Firebug advertises the capability to do something similar via its "DOM Inspector," whenever I try to modify any of the DOM values while I've paused the Javascript via its debugger, it simply ignores the new value I enter. After doing some research, it seems that this is a known issue according to this bug report: http://code.google.com/p/fbug/issues/detail?id=1707 .
Theoretically, I could write a program to simply open up an HTTP socket and emulate a browser "user agent," but this seems like a lot of trouble for my purposes. While I'm asking, does anyone know a good Java/C# library with functions/objects that emulate HTTP headers and parse the received HTML/JS? I've long dreamt about the existence of such a library but most of the ones I've tried (Java's Apache HttpClient, C#'s System.Net.HttpWebRequest) are far too low-level to make anything worthwhile with minimal planning and a short period of time.
Thanks in advance for recommendations and advice you can provide!
Not sure if I understand you correctly, but if you want to change the loaded URL you can do that by setting window.location.href.
If your intent is to replace DOM buildins then you will be sad to hear, that most build-in objects (host objects) aren't regular JavaScript objects and their behaviour is not clearly defined. Some browsers may allow you to replace and/or extend some objects while in other browsers they won't be replaceable/extendable at all.
If you want to "script a browser" using JavaScript, you should definitly have a look at node.js and it's http module. There's also a thirdparty module called html5 that simulates the DOM in node.js and even allows the usage of jQuery.