问题
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