Injecting JS functions into the page from a Greasemonkey script on Chrome Injecting JS functions into the page from a Greasemonkey script on Chrome google-chrome google-chrome

Injecting JS functions into the page from a Greasemonkey script on Chrome


The only way to communicate with the code running on the page in Chrome is through the DOM, so you'll have to use a hack like inserting a <script> tag with your code. Note that this may prove buggy if your script needs to run before everything else on the page.

EDIT: Here's how the Nice Alert extension does this:

function main () {  // ...  window.alert = function() {/* ... */};  // ...}var script = document.createElement('script');script.appendChild(document.createTextNode('('+ main +')();'));(document.body || document.head || document.documentElement).appendChild(script);


I have this :

contentscript.js :

function injectJs(link) {var scr = document.createElement('script');scr.type="text/javascript";scr.src=link;document.getElementsByTagName('head')[0].appendChild(scr)//document.body.appendChild(scr);}injectJs(chrome.extension.getURL('injected.js'));

injected.js :

function main() {     alert('Hello World!');}main();


I took a quick look at the alternatives to unsafeWindow on the Greasemonkey wiki, but they all look pretty ugly. Am I completely on the wrong track here or should I look more closely into these?

You should look, because it's only available option. I'd prefer to use location hack.

myscript.user.js:

function myFunc(){  alert('Hello World!');}location.href="javascript:(function(){" + myFunc + "})()"

example.com/mypage.html

<script>myFunc() // Hello World!</script>

Sure, it's ugly. But it's working well.


Content Scope Runner method, mentioned by Max S. is better than location hack, because its easier to debug.