[Edit:我将用一个演示问题的简化示例来替换原来的、令人困惑的问题。]
背景
我正在尝试编写一个将在 Chrome 中运行的用户脚本。该脚本需要调用 JavaScript 函数AlertMe()
它位于用户脚本之外——此函数是页面的一部分,包含在服务器端动态生成的变量,因此不可能在我的用户脚本中重写此函数。
Code
页面上的脚本 (访问页面 http://martinsmucker.com/demo/alertme.html):
<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>
我的用户脚本(在 Chrome 中安装它 http://martinsmucker.com/demo/martinsmucker.user.js):
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.
永远并且永远不会调用该函数。如果您输入typeof AlertMe
进入 Chrome 的控制台,它会正确响应"function"
,那么为什么我的用户脚本总是认为AlertMe
是未定义的?
您始终可以编写一个小函数来检查该函数是否已加载
function waitForFnc(){
if(typeof absearch == "undefined"){
window.setTimeout(waitForFnc,50);
}
else{
runMyFunction();
}
}
function runMyFunction(){
var urlParams = window.location.search.substring(1).split('&'),
username = "",
hscEmailInput = document.getElementById('userfield6'),
i = 0;
if (urlParams !== "") {
for (i = 0; i < urlParams.length; i++) {
if (urlParams[i].substr(0,4) === "USER") {
username = urlParams[i].replace('USER=', '');
hscEmailInput.value = username + '@example.com';
absearch('&PAGESIZE=1');
}
}
}
}
waitForFnc();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)