我正在编写一个 Safari 扩展程序,它可以向不属于我的网页添加一些功能。我希望我注入(inject)的 JavaScript 页面能够触发主机页面使用的一些 JavaScript 函数,但它不起作用。在控制台上,我收到消息 ReferenceError: Can't find variable: function_name
。
我的脚本被指定为结束脚本,因此应该加载整个页面。该函数也从页面上的 onclick()
处理程序调用,如下所示:
onclick="function_name($(this).up());"
我可以获得对该页面元素的引用,但是当我调用 element.onclick()
时,我得到另一个错误:TypeError: 'undefined' is not a function (evaluating '$ (this).up()')
.
奇怪的是,当我从 AppleScript 调用 JavaScript 函数时(do JavaScript "function_name()"in page
)它工作正常。如何触发这些功能?
最佳答案
我可以扩展 canisbos 的答案。您可以使用 PostMessage 函数与插入的脚本通信。
注入(inject)脚本:
//insert script to page
var myScriptElement = document.createElement('script');
myScriptElement.innerHTML =
'window.addEventListener("message", function(e) {' +
' if (e.data.msg == "do") {' +
' foo(e.data.info);' +
' postMessage({msg: "done", info: "answer"}, "*");' +
' };' +
'}, false);'
document.querySelector('head').appendChild(myScriptElement);
//add answers listener
window.addEventListener('message', function(e) {
if (e.data.msg == 'done') {
console.log(e.data.info);
};
}, false);
//add the testing function on the body click
document.addEventListener('click', function (e) {
//call inserted script
postMessage({msg: 'do', info: 'from inject'}, '*');
}, false);
测试 html 页面:
<html>
<script>
function foo(text) {
console.log(text);
};
</script>
<body>
<button id='button' onclick='foo("from page")'>test</button>
</body>
</html>
关于javascript - 从注入(inject)的页面执行主机脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8927887/