unsafeWindow
API was made so that userscripts could interact with the variables and functions of the pages the script executed on. However it is strongly discouraged as websites could then hijack userscripts through unsafeWindow
and make them execute malicious code. However, why was unsafeWindow
even necessary and why is it still used? Previously until Firefox 39, users were able to use the location hack as an alternative to unsafeWindow
. This hack eventually stopped working due to an update in Firefox 39 which patched this. Despite this, users could still use GM APIs in the isolated sandbox and insert code through a script tag like this:
const fnToRunOnNativePage = () => {
console.log('fnToRunOnNativePage');
};
const script = document.body.appendChild(document.createElement('script'));
script.textContent = '(' + fnToRunOnNativePage.toString() + ')();';
// to use information inside the function that was retrieved elsewhere in the script,
// pass arguments above
script.remove();
I got this code from this stackoverflow post: How do I make my userscript execute code in isolated sandbox and unsafeWindow too?
So why is unsafeWindow
is still useable? The code above is an almost perfect alternative to unsafeWindow
. Also as a side note, is there any difference in the way unsafeWindow
runs in Greasemonkey and Tampermonkey? Thanks.
External Resources: