1

I am writing a chrome extension, using a content script to inject some javascript code. As follows:

let actualCode = 'My Injected JS Code';
let script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);

For the injected script, I would like to use some value stored in chrome.storage.sync. However, I found that the API is unaccessible to the injected script (storage.sync is undefined). The API is only accessible within the content script, but not for the injected script. Any ideas how I could access chrome.storage API for the injected script too?

PS: I've registered the storage API in manifest.json

PS: When I open the developer's console on chrome and type "chrome.storage", it returns undefined too. I think this might be a permission problem?

KaiJun
  • 97
  • 9
  • Access the storage in the content script, then use DOM messaging to send it to the injected script as shown [here](https://stackoverflow.com/a/19312198). – wOxxOm Dec 24 '20 at 12:46

2 Answers2

1

The inject way you used for the script, made it work in the web page environment, which doesn't have access to most of Chrome Extensions API.

However, there is an option to use Messages API which allows sending requests from a webpage to the extension by ID. In this case, you also need to implement a listener in your background page, to answer such requests.

P.S. chrome.storage API also shouldn't be available from page console. You may want to debug it from your background page console or select a content script environment (if the extension has such):

Select content script env in devtools
Denis L
  • 3,209
  • 1
  • 25
  • 37
  • Thanks for the help! The sendMessage API couldn't work as I will need a listener on the content script, where onMessageExternal API couldn't work on a content script. Any ideas how to go about this issue? – KaiJun Dec 30 '20 at 18:50
  • @KaiJun a first idea: you can try using the poll technique, where you're asking about new updates every milliseconds. – Denis L Dec 30 '20 at 20:44
0

you can use window.postMessage({type : "MESSAGE_NAME"}) in injected script to send "message" event. then use windows.addEventListner("message", callback) in content_script to listen on "message" event.

You can specify the type of message to which you want to listen in the callback function. for instance

in content_script.js

function func_callback(){
  if (event.data.type && event.data.type === "MESSAGE_NAME") {
   # Your code
  }`enter code here`
}

windows.addEventListner("message", func_callback)

in injected_script.js

<button onClick={()=>window.postMessage({type : "MESSAGE_NAME"})}></button>
Fauzan Taufik
  • 189
  • 3
  • 5