(我已经阅读了this,但没有成功,我做了很多搜索和实验,但无济于事。)
我正在编写一个 Chrome 扩展程序 (BigConsole),目的是为 Chrome 开发人员工具构建一个更好的控制台选项卡。这意味着我想在页面上下文中执行用户输入代码,并访问页面上的 DOM 和其他变量。为此,通信结构如下:
devtools
创建一个 panel
用户写代码的地方panel
的代码时, panel
向 background
发送消息代码为 background
脚本从 panel
接收消息/代码并将其传递给 content
注入(inject)页面的脚本content
脚本从 background
接收消息/代码脚本并注入(inject) script
元素进入页面,然后运行代码 script
的结果然后将页面上的内容发回 content
带有 window.postMessage 的脚本 content
脚本从页面监听消息/结果并将其传递给 background
脚本 background
脚本从 content
接收消息/结果脚本并将其传递给 panel
panel
接收来自 background
的消息/结果脚本并将其插入结果日志唷。
现在,当用户尝试运行代码时,什么也没有发生。我放了一堆
console.log()
s 进入代码,但控制台中没有任何内容。我的主要问题是,我在这里做错了什么消息传递导致什么都没有发生?或者,我很乐意被告知我让这种方式过于复杂,并且有更好的做事方式。下面的简化代码...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) {}
});
};
背景.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); }
最佳答案
正如亚历克斯所指出的,您的代码中有一个错字,导致它无法正常工作。
删除您当前的代码并使用 chrome.devtools.inspectedWindow.eval
直接运行代码并解析结果。这将您的复杂逻辑简化为:
PS。有一种方法可以操纵现有的控制台,但我建议不要使用它,除非它是供个人使用的。 this answer 中显示了两种不同的方法。 .
关于javascript - 在 Chrome DevTools 和扩展中的内容脚本之间进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17508634/