繁体   English   中英

从注入的页面执行主机脚本

[英]Executing host script from an injected page

我正在编写一个Safari扩展,它为我不拥有的网页添加了一些功能。 我希望我注入的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 )时,它工作正常。 我该如何触发这些功能?

它不起作用,因为扩展的注入脚本是沙盒; 除了DOM之外,它无法看到页面的全局对象(反之亦然)。 解决此安全限制的一种方法是让注入的脚本使用您需要的语句创建<script>元素并将其插入到文档中。 例如:

var myScriptElement = document.createElement('script');
myScriptElement.innerHTML = 'alert("Page is using jQuery " + $.fn.jquery)';
document.querySelector('head').appendChild(myScriptElement);

但是,插入的脚本也无法访问注入的脚本的对象。 因此,例如,如果您尝试从插入的脚本访问扩展的safari对象,您将收到引用错误。

我可以从canisbos扩展答案。 您可以使用PostMessage函数与插入的脚本进行通信。

注入脚本:

//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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM