由于注入(inject)的脚本无法执行我尝试过的跨域 xmlhttp 请求,因为手册中建议将消息从注入(inject)的脚本发送到后台脚本以使其完成这项工作。但我无法让消息发挥作用。
这是我的代码,只有三个文件,扩展名尽可能简单。
config.xml
<?xml version="1.0" encoding="utf-8"?>
<widget xmlns="http://www.w3.org/ns/widgets" id="http://www.example.org/helloworld">
<name>postMessage-testcase</name>
<description>check if opera's postMessage fails</description>
</widget>
index.html
<!doctype html>
<html lang="en">
<head>
<script>
opera.extension.onmessage = function(event) {
alert("get the message!");
opera.extension.postMessage("posting reply");
};
</script>
</head>
<body></body>
</html>
includes/user.js
// ==UserScript==
// @include *apod.nasa.gov*
// ==/UserScript==
opera.extension.onmessage = function(event) {
alert("got reply !");
};
alert("yep, I'm on apod, proceeding with messages");
opera.extension.postMessage("message body");
当用户打开 apod.nasa.gov 时,脚本应该来回发送消息,但这里只发送一条消息,没有发生消息传递,控制台中也没有显示错误。
最佳答案
无法从后台进程调用 opera.extension.postMessage()
方法,因为它不知道将消息发布到哪个页面/选项卡。相反,opera.extension.broadcastMessage()
可用于向所有选项卡发送消息(请参阅: http://dev.opera.com/articles/view/extensions-api-messaging-broadcastmessage/ )
或者,向特定选项卡中注入(inject)的脚本发送消息:
- 在后台进程中监听连接事件 (
opera.extension.onconnect
) - 从事件的
source
对象运行postMessage()
参见:http://dev.opera.com/articles/view/opera-extensions-messaging/#backgroundscript_injectedscript
顺便说一句,不要忘记,在后台进程中使用跨域 XHR,您需要在 config.xml 文件中允许访问目标域,例如:
<access origin="http://apod.nasa.gov" subdomains="true"/>
关于javascript - 为什么 Opera 12 中后台脚本和注入(inject)脚本之间无法发布消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11456040/