29

I have a very simple greasemonkey script that I want to call an already existing javascript function on the page. I've read the documentation and nothing seems to work

window.setTimeout(function() { 
    alert('test') // This alert works, but nothing after it does
    myFunction() // undefined
    window.myFunction() // undefined
    document.myFunction() // undefined
}, 1000);

3 Answers 3

28

Try using: unsafeWindow.myFunction();

More details and info - http://wiki.greasespot.net/UnsafeWindow

3
  • Thanks, I'm marking your answer as the accepted answer because the link provides some alternatives. I found that attaching the script to the page is really the best solution for what I need.
    – Asa Ayers
    Jan 14, 2009 at 17:13
  • 1
    I would suggest using locaction.href = 'javascript:...' instead of unsafeWindow if you want your script to be more compatible (ive had some problems with unsafeWindow TamperMonkey for Chrome) Nov 24, 2012 at 21:05
  • unsafeWindow not defined Oct 15, 2021 at 11:59
18

One way to call a function in the original page is like this:

location.href = "javascript:void(myFunction());";

It is a bit ugly. There is also the unsafeWindow provided by GreaseMonkey too, but the authors advise against using it.

unsafeWindow.myFunction();

Looks neater but make sure you understand the ramifications. From the manual:

unsafeWindow bypasses Greasemonkey's XPCNativeWrapper-based security model, which exists to make sure that malicious web pages cannot alter objects in such a way as to make greasemonkey scripts (which execute with more privileges than ordinary Javascript running in a web page) do things that their authors or users did not intend. User scripts should therefore avoid calling or in any other way depending on any properties on unsafeWindow - especally if if they are executed for arbitrary web pages, such as those with @include *, where the page authors may have subverted the environment in this way.

In other words, your script elevates the privileges available to the original page script if you use unsafeWindow.

1
  • location.href = "javascript:..." is the better way in most cases Nov 24, 2012 at 21:06
7

You could try using javascript event listeners.

These execute code on response to object events occurring (such as page load)

For example, to execute code on page load:

window.addEventListener('load', function () 
{
    /* code goes here */
});
2
  • addEventListener is missing a closing ')' parenthesis after the '}'.
    – elig
    Sep 4, 2020 at 19:29
  • I have just fixed the syntax, thank you. Oct 15, 2021 at 12:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.