Saturday, 29 July 2023

How is unsafeWindow implemented by user script extensions?

Today I came across a situation where I need to make an extension to monkey-patch some objects in a web page.

However I found little to none documentation on how it can actually be achieved, I've tried using the userScripts API (currently exclusive to Firefox) but the window object is contextually isolated from the window on the HTML DOM of the page.

I know that this is possible because user script managers like GreaseMonkey implement an unsafeWindow object which gives the script direct access to objects in the unisolated context of the web page, thus making monkey-patching very easy.

So I would like to know how this is actually achieved. I've attempted to study the source code of an user script manager called ViolentMonkey, I found that it defines unsafeWindow in src/injected/web/gm-api-wrapper.js:53 as a reference to the global object but I could not locate where this in turn is defined in the source code.

I know that this is not implemented by simply injecting a <script> element in the page because none is visible in the page's DOM upon my inspection.

I'm very curious about the implementation of this cool mechanism, I'm pretty sure I missed something obvious so I need your help to remove my blind-folds!



from How is unsafeWindow implemented by user script extensions?

No comments:

Post a Comment