Chrome Extension: How do I get a web page to access functions defined by my content script?

夙愿已清 提交于 2021-01-28 21:39:00

问题


I'm programming a Chrome Extension, and I'm having it inject a content script which iterates through a few elements and attaches an onclick property to them which sends a message to my background script to execute a custom function on the DOM (the function defined in content scripts). To send a message from the web page to the extension, I must specify the extension ID which, as of now, I was manually getting from the extensions menu. Could I manage to query something for the extension's own ID so I can inject code that would talk to my content script? Is there another way to do what I'm trying to do?

The code injected into the DOM for each of these elements looks like this

targets[current].element.setAttribute("onclick", `chrome.runtime.sendMessage(${EXTENSION_ID}, this.id)`);

回答1:


There are many ways to exhange information between the specific tab you're viewing and your background script. You can check those out on this answer.

The solution to your Chrome extension ID problem is using chrome.runtime.id to get the extension ID and inject it alongside your other code into the required page and then using it to send a message back.



来源:https://stackoverflow.com/questions/65375452/chrome-extension-how-do-i-get-a-web-page-to-access-functions-defined-by-my-cont

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