问题
I need to pass a message (raise an event) in a Chrome extension, and have JavaScript on a webpage react to it.
In content_script.js
of the extension, there should be a function like
raiseXYZevent(data);
JavaScript on the webpage http://foo.com/mypage.html
should execute a handler
function processXYZevent(data) { ... }
The problem is that content script within an extension cannot interact with JavaScript on the webpage directly (it can only modify DOM). Is there a way to make DOM changes from the extension, somehow detect them from the webpage and call processXYZevent
?
回答1:
Since the content script and the webpage share the same DOM, you can use postMessage
to send messages between them. The Chrome API documentation explains this in detail with examples.
来源:https://stackoverflow.com/questions/19035159/pass-a-message-from-chrome-extension-to-webpage