Pass a message from Chrome Extension to Webpage

蓝咒 提交于 2019-12-19 20:37:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!