Hijacking a variable with a userscript for Chrome
In Content scripts (Chrome extensions), there's a strict separation between the page's global window
object, and the content script's global object.
- To inject the code, a script tag has to be injected.
- Overwriting a variable is straightforward.
Overwriting a variable, with the intention of preventing the variable from being overwritten requires the use ofObject.defineProperty
Example + notes.
The final Content script's code:
// This function is going to be stringified, and injected in the pagevar code = function() { // window is identical to the page's window, since this script is injected Object.defineProperty(window, 'smilies', { value: true }); // Or simply: window.smilies = true;};var script = document.createElement('script');script.textContent = '(' + code + ')()';(document.head||document.documentElement).appendChild(script);script.parentNode.removeChild(script);