(我已阅读this,并没有工作,我已经做了很多搜索和实验都无济于事。)在扩展的Chrome DevTools和内容脚本之间的沟通
我写的是Chrome扩展程序(BigConsole),目标是为Chrome开发人员工具构建更好的“控制台”选项卡。这意味着我想在页面的上下文中执行用户输入的代码,以访问页面上的DOM和其他变量。要做到这一点,通信的结构如下:
devtools
创建panel
其中用户编写代码- 当用户想要从
panel
执行代码,所述panel
发送一个消息给一个background
脚本代码 - 的
background
脚本从panel
接收消息/码并将其传递到content
脚本将其注入到所述页面 - 的
content
脚本recei VES从background
脚本消息/代码和注入一个script
元件到其中,然后运行该代码 - 的
script
在页面上的结果然后回发到content
脚本window.postMessage - 的
content
的页面脚本侦听来自该网页的信息/结果并将其传递到background
脚本 - 的
background
脚本接收消息/从content
脚本导致并将其传递到panel
- 的
panel
接收messag从background
脚本E /导致并将其插入到日志结果
呼的。
现在,当用户试图运行代码时,没有任何反应。我在代码中放了一堆console.log()
,但控制台中没有任何东西出现。我的主要问题是,我在这里做了什么错误的消息传递,导致什么都没有发生?或者,我很乐意被告知我这样做太复杂,并且有更好的做事方式。下面简化代码...
panel.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) {}
});
};
background.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);
});
});
content.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); }
太棒了,谢谢!奖励点不仅仅是让我更好地正式做到这一点,而且是非正式的更好的方式。 :) – IceCreamYou