Mic*_*ker 7 javascript google-chrome userscripts
[ 编辑:我用一个简单的例子来代替原来的,令人困惑的问题来证明这个问题.]
背景
我正在尝试编写一个将在Chrome中运行的用户脚本.这个脚本需要调用一个AlertMe()在usercript之外的JavaScript函数- 这个函数是页面的一部分,包含在服务器端动态生成的变量,所以不能在我的函数中重写这个函数. userscript.
码
页面上的脚本(访问页面):
<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>
Run Code Online (Sandbox Code Playgroud)
我的用户脚本(在Chrome中安装):
function tryAlert()
{
if (typeof AlertMe == "undefined") {
console.log('AlertMe is undefined.');
window.setTimeout(tryAlert, 100);
}
else {
AlertMe();
}
}
tryAlert();
Run Code Online (Sandbox Code Playgroud)
问题
当我试图简单地调用该功能时,Chrome的控制台让我知道AlertMe is not defined.认为这是因为我的用户脚本在加载所有其他脚本之前运行,我曾经setTimeout等待AlertMe函数被定义.
不幸的是,如果您安装脚本然后访问该页面,您将看到这只是AlertMe is undefined.永远输出并且从不调用该函数.如果您输入typeof AlertMeChrome的控制台,它会正确回复"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();
Run Code Online (Sandbox Code Playgroud)
这不是时间问题.
您正在遇到Greasemonkey的安全限制,这会阻止您在页面中执行功能.请参阅我之前的问题的答案,以获得解释和一些安全的解决方法:
UserScripts&Greasemonkey:调用网站的JavaScript函数