(I already read this one and it didn’t work, and I searched and experimented a lot to no avail.)
I am writing a Chrome extension ( BigConsole ) with the goal of creating a better Console tab for the Chrome Developer Tools. This means that I would like to execute user-entered code in the context of the page with access to the DOM and other variables on the page. For this, the relationship is structured as follows:
devtools creates a panel where the user writes code- When a user wants to execute code from
panel , panel sends a message to the background script with code background script receives the message / code from panel and passes it to the content script, which is entered on the pagecontent script receives the message / code from the background script and injects the script element into the page, which then runs the code- The result of the
script on the page is then sent back to the content script using window.postMessage content script listens for the message / result from the page and passes it to the background scriptbackground script receives the message / result from the content script and passes it to the panelpanel receives a message / result from the background script and inserts it into the result log
Phew
Now, when the user tries to run the code, nothing happens. I put a bunch of console.log() in the code, but nothing appears in the console. My main question is: what did I do wrong here with the transmission of the message, which does not lead to the fact that nothing happens? As an alternative, I would really like to be told that I am doing it too hard, and there is a better way to do something. Simplified code below ...
panel.js:
window.onload = function() { var port = chrome.runtime.connect({name: "Eval in context"});
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); }
source share