How can I get greasemonkey to call a function on a page after it loads

前端 未结 3 1950
天涯浪人
天涯浪人 2021-01-31 17:51

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

相关标签:
3条回答
  • 2021-01-31 17:55

    Try using: unsafeWindow.myFunction();

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

    0 讨论(0)
  • 2021-01-31 18:14

    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.

    0 讨论(0)
  • 2021-01-31 18:18

    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 */
    }
    
    0 讨论(0)
提交回复
热议问题