Mat*_*cas 1 javascript google-chrome google-chrome-extension
我正在学习建立Chrome扩展,而我试图按照官方指南中的指令之一在这里.
我想要完成的是:
到现在为止还挺好!我使用以下脚本注入页面.
var injectJS = function(url, cb) {
var h = document.getElementsByTagName('head')[0],
s = document.createElement('script');
s.type = 'text/javascript';
s.src = url;
if (cb)
s.onload = cb;
h.appendChild(s);
};
injectJS(chrome.extension.getURL('script/do_something.js'));
Run Code Online (Sandbox Code Playgroud)
现在,我希望注入的脚本能够与扩展进行通信.
看起来我正在寻找的是文档中描述的内容.
https://developer.chrome.com/extensions/content_scripts.html#host-page-communication
问题是,当我尝试执行window.postMessage
控制台时显示错误"DOM Exception 12".
编辑:解决了运行示例代码的第一个问题.
我得到的另一个错误,来自smae代码来自port.postMessage
:
Uncaught Error: Attempting to use a disconnected port object
这是代码:
var port = chrome.runtime.connect();
// Respond to messages from the injected script to collect results
window.addEventListener('message', function(e) {
if (e.source != window)
return;
if (e.data.type && (e.data.type == 'FROM_PAGE')) {
console.log('Content script received: %s', e.data.text);
port.postMessage(e.data.text);
}
}, false);
Run Code Online (Sandbox Code Playgroud)
基本上我试图在页面重新加载时暂时保留一些数据.内容脚本/注入脚本收集数据,然后加载下一页.后台脚本应保存结果,直到所有页面都已加载.
不要混淆port.postMessage
contentscript.js示例中的window.postMessage
.
port.postMessage
是Chrome扩展程序特定的API,用于在扩展程序中传递消息,同时window.postMessage
是用于与框架通信的JavaScript方法.第二个参数window.postMessage
是必需的,用于验证目标是否允许接收消息.
在您的情况下,使用通配符可能就足够了,因为您正在从页面向自身发送消息:
window.postMessage({ type: "FROM_PAGE", text: "Hello from the webpage!" }, "*");
^^^
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3444 次 |
最近记录: |