Javascript引用错误,但我使用bookmarklet时工作

问题描述 投票:0回答:2

我正在尝试在已经完全加载的页面上执行一些Javascript。

为了测试javascript,我创建了一个bookmarklet,在页面加载时单击它,并且它正确执行:

javascript:(array.find('value').__showAllRecords(event))

我想在AppleScript中使用这个Javascript,我正在写它将它发送到chrome,但由于某种原因,我收到了这个错误:

Uncaught ReferenceError: array is not defined
    at <anonymous>:1:1

它只发生在我在AppleScript编辑器中运行脚本时,而不是在我使用书签时。这是我的AppleScript代码:

tell application "Google Chrome"
    execute front window's active tab javascript "array.find('value').__showAllRecords(event)"
end tell
javascript applescript referenceerror
2个回答
0
投票

变量array是在脚本执行后的某个时间点创建的,因为您不知道何时可以重试,直到它存在:

(function(){
  function trySomething(){
    try{
      array.find('value').__showAllRecords(event);
      console.log("worked, stop trying");
      clearInterval(timer);
    }catch(e){
      console.log("didn't work, try again",e);
    }
  }
  var timer = setInterval(trySomething,1000);
}())

//create the array object some time in the future (not actually an Array type)
//this is not part of your script but would be created by the page
//at some point
setTimeout(
  ()=>window.array={find:x=>({__showAllRecords:x=>x})}
  ,6000
)

0
投票

不幸的是,applescript无法访问非默认的全局变量。看到线程https://bugs.chromium.org/p/chromium/issues/detail?id=543437

但是有一种解决方法,你可以做的是将数组设置为div的innerHTML并从applescript中检索值。因此对于例如这是我的div <div id="test">[1,2,3]</div>,你可以执行

tell application "Google Chrome"
    execute front window's active tab javascript "console.log(document.getElementById(\"test\").innerHTML)"
end tell

希望这可以帮助

© www.soinside.com 2019 - 2024. All rights reserved.