(我已经读过this但它不起作用,我做了很多搜索和实验都无济于事。)
我正在编写一个 Chrome 扩展(大控制台),目标是为 Chrome 开发者工具构建更好的控制台选项卡。这意味着我想在页面上下文中执行用户输入代码,并访问页面上的 DOM 和其他变量。为此,通信结构如下:
-
devtools
创建一个panel
用户编写代码的地方
- 当用户想要执行代码时
panel
, the panel
发送消息至background
带有代码的脚本
- The
background
脚本接收来自的消息/代码panel
并将其传递给content
注入到页面的脚本
- The
content
脚本接收来自的消息/代码background
脚本并注入script
元素插入页面,然后运行代码
- 结果
script
然后将页面上的内容发布回content
带有 window.postMessage 的脚本
- The
content
脚本侦听来自页面的消息/结果并将其传递到background
script
- The
background
脚本接收来自的消息/结果content
脚本并将其传递给panel
- The
panel
接收来自的消息/结果background
脚本并将其插入结果日志中
Whew.
现在,当用户尝试运行代码时,什么也没有发生。我放了一堆console.log()
进入代码但控制台中没有任何显示。我的主要问题是,我在消息传递方面做错了什么,导致什么也没有发生?或者,我很乐意被告知我让这种方式变得太复杂了,并且有更好的做事方式。下面的简化代码...
面板.js:
window.onload = function() {
var port = chrome.runtime.connect({name: "Eval in context"});
// Add the eval'd response to the console when the background page sends it back
port.onMessage.addListener(function (msg) {
addToConsole(msg, false);
});
document.getElementById('run').addEventListener('click', function() {
var s = document.getElementById('console').value;
try {
// Ask the background page to ask the content script to inject a script
// into the DOM that can finally eval `s` in the right context.
port.postMessage(s);
// Outputting `s` to the log in the panel works here,
// but console.log() does nothing, and I can't observe any
// results of port.postMessage
}
catch(e) {}
});
};
背景.js:
chrome.runtime.onConnect.addListener(function (port) {
// Listen for message from the panel and pass it on to the content
port.onMessage.addListener(function (message) {
// Request a tab for sending needed information
chrome.tabs.query({'active': true,'currentWindow': true}, function (tabs) {
// Send message to content script
if (tab) {
chrome.tabs.sendMessage(tabs[0].id, message);
}
});
});
// Post back to Devtools from content
chrome.runtime.onMessage.addListener(function (message, sender) {
port.postMessage(message);
});
});
内容.js:
// Listen for the content to eval from the panel via the background page
chrome.runtime.onMessage.addListener(function (message, sender) {
executeScriptInPageContext(message);
});
function executeScriptInPageContext(m) { alert(m); }