Sandboxed DOM API

Description

I finally sat down and started work on a sandboxed DOM API. Originally I was just going to develop a new framework because the DOM is messy but instead I decided it would be cool to have a safe simulated DOM instead and build a framework on top of that.

It isn’t complete yet and there’s still a lot of work to do but it’s working pretty good. I still need to run some tests on it and try to break it but I don’t have time at the moment as I need to do other stuff.

One of the problems making a DOM API is that IE doesn’t have setter support even in IE8 it doesn’t allow you to define setters on normal objects. Because I spend most of my time hacking stuff it was a fun challenge to make IE support setters on DOM objects and keep my sandboxed whitelists.

It’s quite complicated and quite ugly in parts but it works and I think it’s the only way to support legacy browsers like IE7.

How it works

I have to test for the various setter support including defineSetter, Object.defineProperty and revert to the legacy onpropertychange. Object.defineProperty works fine in IE8 when using a DOM object but I encountered problems when I needed to assign to a sandboxed normal object. Here it gets ugly, I had to create a DOM object for any styles used by a node, this way both Object.defineProperty and onpropertychange allow me to monitor any assignments to the fake style object.

var styles = document.createElement('span');
node.$style$ = styles; 
Object.defineProperty(node.$style$, '$'+cssProp+'$', {});
document.getElementById('styleObjs').appendChild(styles);
node.$style$ = styles; 
node.$style$.onpropertychange = function(){}

As you can see with the code sample above I have to append the fake style DOM object for onpropertychange otherwise it won’t be called on assignments.

You can see this working by using the following test code:-

document.getElementById('x').style.color='#ccc';

So I proxy off all these functions and make the root node any HTML object, I use CSSReg and HTMLReg to sandbox each modification to a property. Finally where it got complicated was supporting events, currently I only support “onclick” as I’m still testing but what happens is because the code is already sandboxed I don’t need to perform a rewrite so I pass this to JSReg as it’s already been converted, I supply the “this” object as the HTML element this allows the triggered event to call “this” as the current element.

That’s it! I’ve donated the code to OWASP and it will be free to use in your projects, any help testing or suggestions are most welcome, enjoy the demo!

Sandboxed DOM API

Comments are closed :( too much spam. If you want to contact me about any article please email or tweet me.