Chrome DevTools和扩展中的内容脚本之间的通信
Communicating between Chrome DevTools and content script in extension
(我已经读过了,但它不起作用,我做了很多搜索和实验,但都无济于事。)
我正在编写一个Chrome扩展(BigConsole),目的是为Chrome开发工具构建一个更好的控制台选项卡。这意味着我希望在页面的上下文中执行用户输入代码,并访问页面上的DOM和其他变量。为此,通信结构如下:
devtools
创建用户编写代码的panel
- 当用户想要执行来自
panel
的代码时,panel
向带有代码的background
脚本发送消息 background
脚本接收来自panel
的消息/代码,并将其传递给注入页面的content
脚本content
脚本从background
脚本接收消息/代码,并将script
元素注入页面,然后页面运行代码- 页面上
script
的结果随后通过window.postMessage发布回content
脚本 content
脚本侦听页面中的消息/结果,并将其传递给background
脚本background
脚本从content
脚本接收消息/结果,并将其传递给panel
panel
从background
脚本接收消息/结果,并将其插入结果日志
Whew。
现在,当用户尝试运行代码时,什么都没有发生。我在代码中放入了一堆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); }
正如Alex所指出的,您的代码中有一个拼写错误,导致它无法工作。
删除当前代码,使用chrome.devtools.inspectedWindow.eval
直接运行代码并解析结果。这将您复杂的逻辑简化为:
- devtools创建一个面板,用户可以在其中编写代码
- devtools运行代码
- devtools处理结果
PS。是一种操作现有控制台的方法,但我建议不要使用它,除非它是个人使用的。这个答案显示了两种不同的方法。
相关文章:
- 如何在弹出脚本到内容脚本之间发送消息并返回
- Firefox插件SDK:在侧边栏和主脚本之间通信对象
- 函数在两个或多个脚本之间进行访问
- 在这种特殊情况下,在PHP脚本之间传递值
- Chrome扩展:在后台页面和网站页面脚本之间进行通信的最佳方法
- 如何在Chrome扩展弹出窗口和内容脚本之间发送消息
- 从java脚本到C#的回调,C#和java脚本之间的异步编程
- 不了解插件和脚本之间的区别
- 原型:这两个脚本之间的区别
- 应用程序与 Web 视图中注入的脚本之间的通信
- 执行套件时脚本之间的超时 - 量角器非角度
- Chrome 扩展程序:无法让消息传递在后台脚本和内容脚本之间正常工作
- 在Chrome内容脚本和弹出脚本之间共享redux存储
- 带类型的<脚本>标记和不带类型的<脚本>之间的区别
- 使用jquery.on()方法处理同一元素(选项标记)的两个脚本之间的冲突
- 如何在Chrome扩展中的内容脚本之间重复使用代码
- 这些脚本之间的效率有差异吗
- 在两个独立的脚本之间共享变量
- chrome扩展中的可变范围,尤其是在背景页和内容脚本之间
- Chrome DevTools和扩展中的内容脚本之间的通信