【发布时间】:2011-02-23 15:10:19
【问题描述】:
[编辑:我用一个简单的例子来代替原来的、令人困惑的问题。]
背景
我正在尝试编写一个将在 Chrome 中运行的用户脚本。此脚本需要调用用户脚本之外的 JavaScript 函数 AlertMe() - 此函数是页面的一部分,包含在服务器端动态生成的变量,因此无法重新编写我的用户脚本中的函数。
代码
页面上的脚本 (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>
我的用户脚本(install it in Chrome):
function tryAlert()
{
if (typeof AlertMe == "undefined") {
console.log('AlertMe is undefined.');
window.setTimeout(tryAlert, 100);
}
else {
AlertMe();
}
}
tryAlert();
问题
当我尝试简单地调用该函数时,Chrome 的控制台让我知道 AlertMe is not defined。认为这是因为我的用户脚本在所有其他脚本加载之前运行,我使用setTimeout 等待AlertMe 函数被定义。
不幸的是,如果您安装脚本然后访问该页面,您会看到这只会永远输出AlertMe is undefined. 而不会调用该函数。如果你在 Chrome 的控制台中输入typeof AlertMe,它会正确响应"function",那为什么我的用户脚本总是认为AlertMe 未定义?
【问题讨论】:
标签: javascript google-chrome userscripts