Sva*_*rog 5 javascript google-chrome google-chrome-extension content-script
我正在编写一个 Chrome 扩展程序,为用户访问的某些页面添加功能。
为此,我需要注入页面需要能够调用的一些变量和函数。
这些变量/函数是在内容脚本中生成的。
但是,由于内容脚本在隐蔽的环境中运行,因此主机页面无法访问它。
根据这篇文章:
http://code.google.com/chrome/extensions/content_scripts.html#host-page-communication
内容脚本和主机页面可以通过添加事件通过 DOM 进行通信。
但这是一种可怕的做事方式,我真的很想看到一些轻松注入方法/变量的方法。
有这样的可能吗?
谢谢!
如果有人仍然感兴趣,我找到了一种通过消息在内容脚本和页面本身之间进行通信的解决方案。
发送脚本中类似这样的内容:
window.postMessage({ type: "messageType", params: { param: "value", anotherParam: "value" } }, "*"/*required!*/);
Run Code Online (Sandbox Code Playgroud)
然后在接收脚本上执行如下操作:
window.addEventListener("message", function(event) {
// We only accept messages from ourselves
if (event.source != window)
return;
switch (event.data.type) {
case "blabla":
// do blabla
// you can use event.data.params to access the parameters sent from page.
break;
case "another blabla":
// do another blabla
break;
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2629 次 |
| 最近记录: |