Ice*_*You 5 javascript-events google-chrome-extension google-chrome-devtools
(我已经读过这篇文章并且它没有用,我做了大量的搜索和实验但没有用.)
我正在撰写Chrome扩展程序(BigConsole),目标是为Chrome开发人员工具构建更好的控制台标签.这意味着我想在页面上下文中执行用户输入的代码,可以访问页面上的DOM和其他变量.为此,通信结构如下:
devtools创建panel用户编写代码的位置panel时,panel将消息发送到一个background脚本的代码background脚本从接收消息/码panel并将其传递到content将其注入到所述页面脚本content脚本从脚本接收消息/代码,background并将一个script元素注入页面,然后运行代码script然后content使用window.postMessage 将页面上的结果发回到脚本content脚本侦听页面中的消息/结果并将其传递给background脚本background脚本从脚本接收消息/结果content并将其传递给panelpanel从接收到该消息/结果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) {}
});
};
Run Code Online (Sandbox Code Playgroud)
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);
});
});
Run Code Online (Sandbox Code Playgroud)
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); }
Run Code Online (Sandbox Code Playgroud)
正如亚历克斯所指出的,这是代码中的一个错误,它阻止它工作.
删除当前代码并使用chrome.devtools.inspectedWindow.eval直接运行代码并解析结果.这简化了您复杂的逻辑:
PS.这里是一个方法来处理现有的控制台,但我建议不要使用它,除非是供个人使用.这个答案显示了两种不同的方法.
| 归档时间: |
|
| 查看次数: |
2731 次 |
| 最近记录: |