1

Hello guys,

I want to be able to access informations stored in chrome.storage.sync from an inline script within a web page, injected by my extension.

When trying to use chrome.storage.sync, sync can't be called from "undefined". In the same way, I couldn't call chrome.runtime.sendMessage. This answer taught me I can't access Chrome APIs from an injected script.

I found out that I could eventually call sendMessage using this technique : https://developer.chrome.com/extensions/messaging#external-webpage and then I could return the wanted data in the callback.

But I wanted to know, is there a better way to do this ? Accessing chrome.storage data from the injected script ? The fact that I need to use my extension's as an argument is really not great...

Thanks !

Community
  • 1
  • 1
Jeremy Belolo
  • 4,319
  • 6
  • 44
  • 88

1 Answers1

3

Since your injected script is essentially the same as the page's own code from a security perspective, there's no way to make this task easy.

externally_connectable that you found is one of the ways to do it.

The other way is to talk with the content script itself. You can do so with custom events or window.postMessage.

Xan
  • 74,770
  • 16
  • 179
  • 206
  • Thanks, custom events seems perfect ! – Jeremy Belolo Oct 11 '15 at 09:34
  • 1
    Just beware that the page's own code can spoof it, in theory. – Xan Oct 11 '15 at 09:35
  • Sure. I will add some security checks. Is it possible to get a callback or use a promise to make use of return values ? – Jeremy Belolo Oct 11 '15 at 09:40
  • 1
    Yes, something like a self-deregistering listener (listen for specific message, run `removeEventListener` with a reference to self) can be put in a promise. – Xan Oct 11 '15 at 09:41
  • I'm sorry, you're very kind but I didn't get that hint. I don't succeed in returning to the injected script the data retrieved by the contentScript, not with a callback nor with a promise :( – Jeremy Belolo Oct 11 '15 at 09:56
  • 1
    Make a new question with your requirements (communication from an injected script to the content script with a response as a promise) and we'll figure something out. It'll help others as well. – Xan Oct 11 '15 at 09:58