I was under the impression that the content_scripts were executed right on the page, but it now seems as though there's some sandboxing going on.
I'm working on an extension to log all XHR traffic of a site (for debugging and other development purposes), and in the console, the following sniff code works:
var o = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(){
console.log(arguments, 'open');
return o.apply(this, arguments);
};
console.log('myopen');
console.log(window, window.XMLHttpRequest, window.XMLHttpRequest.prototype, o, window.XMLHttpRequest.prototype.open);
This logs a message everytime an XHR is sent. When I put this in an extension, however, the real prototype doesn't get modified. Apparently the window.XMLHttpRequest.prototype that my script is seeing differs from that of the actual page.
Is there some way around this? Also, is this sandboxing behavior documented anywhere? I looked around, but couldn't find anything.
Although Chrome's Content Script lives in an "isolated world", you could accomplish something similar to what you've requested by inserting a script element into the dom.
As a proof of concept, I used the TamperMonkey Chrome Extension and created this script:
// ==UserScript==
// @name Modify Secret
// @namespace http://your.homepage/
// @version 0.1
// @description enter something useful
// @author You
// @match https://*/*
// @match http://*/*
// @grant none
// ==/UserScript==
console.log(secret);
var el = document.createElement('script');
el.innerHTML = 'secret = "the blue dog"';
document.body.appendChild(el);
Then I navigated to http://s.codepen.io/boomerang/745009c49e60974cf9dba1b070f27d111458064000840/index.html which has this javascript running:
var secret = 'the brown fox';
var secretPrinter = setInterval(function () {
console.log(secret);
}, 1000);
If you inspect the console, one would expect to see 'the brown fox' constantly printed, but instead we have 'the blue dog'.
In general, I think the security concept that the browser is trying to achieve is to prevent the page's environment from accessing the content script's environment. Realizing that, it's not surprising that you could accomplish something like this with a Browser Extension.
You cannot do that. According to the documentation:
However, content scripts have some limitations. They cannot:
- Use chrome.* APIs (except for parts of chrome.extension)
- Use variables or functions defined by their extension's pages
- Use variables or functions defined by web pages or by other content scripts
- Make cross-site XMLHttpRequests
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With