且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

让我的脚本等待其他脚本加载

更新时间:2023-12-05 08:03:46

这不是时间问题。

您遇到Greasemonkey的安全限制,这会阻止您在页面中执行功能。请参阅我对前一个问题的回答,以获得解释和一些安全解决方法: greasemonkey-calling-a-websites-javascript-functions> UserScripts& Greasemonkey:调用网站的JavaScript功能


[Edit: I'm replacing the original, confusing question with a simplified example demonstrating the problem.]

Background

I'm trying to write a userscript which will run in Chrome. This script needs to call a JavaScript function AlertMe() that is outside of the userscript -- this function is part of the page and contains variables that are generated dynamically on the server-side, so it isn't possible to re-write this function in my userscript.

Code

Script on the page (visit the page):

<script type="text/javascript">
    function AlertMe()
    {
        alert("Function AlertMe was called!");
        // then do stuff with strings that were dynamically generated
        // on the server so that I can't easily rewrite this into the userscript
    }
</script>

My userscript (install it in Chrome):

function tryAlert()
{
    if (typeof AlertMe == "undefined") {
        console.log('AlertMe is undefined.');
        window.setTimeout(tryAlert, 100);
    }
    else {
        AlertMe();
    }
}

tryAlert();

The Problem

When I tried to simply call the function, Chrome's console let me know that AlertMe is not defined. Thinking that this was because my userscript was running before all other scripts had been loaded, I used setTimeout to wait for the AlertMe function to become defined.

Unfortunately, if you install the script then visit the page, you'll see that this just outputs AlertMe is undefined. forever and never calls the function. If you type typeof AlertMe into Chrome's console, it will correctly respond with "function", so why is it that my userscript always thinks that AlertMe is undefined?

This is not a matter of timing.

You're bumping into Greasemonkey's security restrictions, which prevent you from executing functions in the page. Please see my answer to this previous question for an explanation and some safe workarounds:

UserScripts & Greasemonkey: calling a website's JavaScript functions