6

I'm currently in the process of writing a userscript for a certain website. What I'm trying to accomplish requires access to the content scope with the page variables and functions.

Standard operating procedure for that sort of thing seems to be a function that injects a new <script> tag into the DOM, like so:

function injectScript(f) {
    var target = document.head || document.documentElement;
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.text = "(" + f.toString() + ")();";

    target.appendChild(script);
    target.removeChild(script);
}

However, this approach doesn't work because the website has a Content Security Policy which prevents the injected script tag from executing! I've also tried the location hack (basically location.href="javascript:someCode()"), but that also counts as an inline script and won't work.

unsafeWindow would be an option that is unfortunately only available with Greasemonkey. Ideally my script should work with Chrome as well. Is there a better way to access page variables?

a cat
  • 654
  • 1
  • 10
  • 17
  • 2
    `unsafeWindow` also works in Chrome if you install and use Tampermonkey -- which you should anyway; it's much better for most tasks than vanilla Chrome userscript. – Brock Adams Mar 03 '14 at 23:50
  • Looks like a GM and TM feature request, or code fork, might be needed. Meanwhile check out [UserCSP](https://addons.mozilla.org/en-US/firefox/addon/newusercspdesign/) for Firefox. There are probably similar extensions for Chrome. – Brock Adams Mar 04 '14 at 00:01
  • 1
    @BrockAdams Thank you, didn't know about Tampermonkey. I guess that'll do if there's no good solution for vanilla Chrome. – a cat Mar 04 '14 at 00:08
  • The **[`GM_addElement()`](https://www.tampermonkey.net/documentation.php#api:GM_addElement)** API should make this possible in Tampermonkey. See the documentation examples for more details. – double-beep Feb 22 '23 at 18:44

0 Answers0