javascript: call an embedded function from a GM script

青春壹個敷衍的年華 提交于 2019-12-01 09:15:23

问题


On a webpage there's

<script>
  function fn982734()
  {
     // some code
  }
</script>

In my Greasemonkey script, I have the following code:

var fn = fields[5].getElementsByTagName("a")[0].getAttribute('onclick').substr(7,11);
console.log(fn); // outputs fn982734 to the firebug console
window[fn]();

This code does not work, and spawns an error in the error console: window[fn] is not a function. However, typing directly into firebug:

var fn = 'fn982734';
window[fn]();

works perfectly. What's going on?


回答1:


The Greasemonkey script is inside a sandbox and Firebug is not. See: "Avoid Common Pitfalls" (in Greasemonkey).

Your GM script would access that function via unsafeWindow. Like so:

unsafeWindow.fn982734();

.
Alternatively,

var fn = 'fn982734';
unsafeWindow[fn]();

Also works -- from inside the Greasemonkey script.




回答2:


I realise that I'm a little late to this question but Please do not encourage the use of unsafeWindow - it is named unsafe for a reason.

The correct alternative would be to use the "location hack" as described on Greasemonkey's Greasepot Wiki. This code should correctly call the function described in the original post:

location.href = "javascript:void(fn982734())";


来源:https://stackoverflow.com/questions/3254112/javascript-call-an-embedded-function-from-a-gm-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!