2

Im injecting a script in webpage via content script. Inside the script I am using chrome.runtime.sendMessage to successfully send a message to background script. However I have the extensionId hardcoded. How would I dynamically inject the extension id in webpage to send messages to background script?

chrome.runtime.sendMessage(extensionIdHardCoded, {
      msg: data
    },
    function(response) {});
atom
  • 157
  • 3
  • 10
  • 1
    Unfortunately, it must be hardcoded. – Daniel Herr Dec 22 '15 at 03:00
  • @DanielHerr are there any security measures I should in this scenario? My extension just manipulated JS on the front end, and has callbacks between the webpage and background script. – atom Dec 22 '15 at 04:26

2 Answers2

12

First off, if you already have a content script, you don't have to use externally_connectable to communicate - you could use custom events to communicate with the content script that would forward it to background.


That said, you can use chrome.runtime.id and pass it to the window context before injecting your script:

var script = document.createElement('script');
script.textContent = "var extensionId = " + JSON.stringify(chrome.runtime.id);
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

/* now inject your script */

Alternatively, you could add an invisible DOM node that would contain the ID as content or some attribute and read that from the injected script.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
  • I took the first route of first injecting the script containing extension id, and then injected other script which needed to use the extension id. if someone needs more info on different ways to inject scripts via content script [refer to this post](http://stackoverflow.com/a/9517879/3862212) – atom Dec 24 '15 at 06:35
1

Use chrome.runtime.id like this:

chrome.runtime.sendMessage(chrome.runtime.id, {
    msg: data
},
function(response) {});
Moin
  • 1,087
  • 1
  • 9
  • 19
  • 2
    You misunderstand the setup. The code executes at the page level, with no access to Chrome API anymore (except fro `sendMessage`). See [Sending messages from web pages](https://developer.chrome.com/extensions/messaging#external-webpage) – Xan Dec 22 '15 at 11:04
  • 1
    Since `chrome.runtime.id` is mentioned and useful though, I'm not going to downvote. – Xan Dec 22 '15 at 11:05