问题
I have been reading over the chrome extension message passing documentation, but I cannot seem to establish communication from within the inspected window.
For example,
chrome.devtools.inspectedWindow.eval('function() {
.
.
.
/* send message to dev-tools panel */
chrome.runtime.sendMessage({foo:"foo"});<-- Uncaught Error: Invalid arguments to connect. Why is the extensionId required within chrome.devtools.inspectedWindow.eval? This made me step back and ask the question.
}')
I have tried leveraging both background and content scripts to listen for these messages, but nothing seems to trigger. My actual implementation is listening for WebSocket traffic, I left that out for brevity. I am able to listen to each request/response, however I cannot seem to establish communication within inspectedWindow.eval. In the end, my goal is to simply communicate with my dev-tools panel so I can update the UI.
Update
I found an interesting repo from someone that faced a similar issue. They however did not seem to find a valid solution. Could it be that this sort of messaging is not allowed by design?
https://github.com/thomasboyt/injectedWindow.eval-communication-sadness
回答1:
You said you considered using a content script.
In that case, you can raise a custom DOM event, and the content script will be able to process it.
// Content script
window.addEventListener("RebroadcastExtensionMessage", function(evt) {
chrome.runtime.sendMessage(evt.detail);
}, false);
// Eval'd code
var message = {/* whatever */};
var event = new CustomEvent("RebroadcastExtensionMessage", {detail: message});
window.dispatchEvent(event);
The downside, of course, is that the page can listen in on those events if it so chooses as well as spoof them. If that's a serious concern, you can include nonces into event names and messages originating from dev tools. But then again, a really hostile page can override CustomEvent
.. In a way, this is not a solvable problem, since anything you inspectedWindow.eval()
fully shares context (and API access) with the page.
来源:https://stackoverflow.com/questions/32500588/is-it-possible-to-message-the-dev-tools-panel-from-within-inspectedwindow-eval