从注入的页面执行脚本主机 [英] Executing host script from an injected page

查看:134
本文介绍了从注入的页面执行脚本主机的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个Safari浏览器扩展,增加了一些功能来一个网页,我没有自己。我想为我注入了JavaScript网页能够激发宿主页面使用了一些JavaScript函数,但它不工作。在控制台我得到的消息的ReferenceError:找不到变量:FUNCTION_NAME

I'm writing a Safari Extension that adds some functionality to a web page that I don't own. I would like for my injected JavaScript page to be able to fire some JavaScript functions the host page uses, but it doesn't work. On the Console I get the message ReferenceError: Can't find variable: function_name.

我的脚本被指定为一个结束脚本,让整个页面应加载。该功能也从的onclick()处理程序调用页面上,像这样:

My script is specified to be an End Script, so the whole page should be loaded. The function is also called from an onclick() handler on the page, like so:

onclick="function_name($(this).up());"

我能到该页面元素的引用,但是当我打电话 element.onclick()我得到另一个错误:类型错误:'未定义不是(评估函数'$(本).UP()')

奇怪的是,当我调用JavaScript函数从一个AppleScript(做的JavaScript函数名()中页),它工作正常。我怎样才能触发这些功能呢?

Oddly, when I call the JavaScript function from an AppleScript (do JavaScript "function_name()" in page) it works fine. How can I trigger these functions?

推荐答案

我可以从canisbos延长答复。你可以用PostMessage函数插入脚本通信。

I can extend answer from canisbos. You can communicate with the inserted script with the PostMessage function.

注入脚本:

//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页面:

Test html page:

<html>
<script>
  function foo(text) {
    console.log(text);
  };
</script>
<body>
  <button id='button' onclick='foo("from page")'>test</button>
</body>
</html>

这篇关于从注入的页面执行脚本主机的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆