0

I'm making a chrome extension that invokes a content script called main.js. The main.js injects a content script content.js into a current web pages DOM <script type="module" src="chrome-extension://xxxxx/content.js"></script>. There are basically some buttons that get inserted onto any web page that you visit and content.js has the function that call an API to get data.

The thing is, when the html button is pressed and makes an API call using the javascript fetch method (I included this method in my content.js file), the origin of the request comes from whatever web page you visit and press the button on. I want to get the API request origin to show as chrome-extension://xxx, and this worked as a test when I put the api call in background.js, for example. So I'm trying to think where I can put the API call function or how to call it so it's not being called as origin from the webpage.

Is there a way that I could "message" some backend component to invoke a function from so the API call to fetch data happens outside of the DOM?

dataviews
  • 2,466
  • 7
  • 31
  • 64
  • 1
    Don't use the script element as it runs the code in the JS environment of the page, which may use spoofed prototypes to extract data from your extension. Use dynamic `import()` to import the code in the safe isolated context as [shown here](/a/53033388). Then you'll simply use [chrome messaging](https://developer.chrome.com/extensions/messaging) to ask the background script to fetch the data ([example](/a/55292071)). Another approach is to add a web_accessible_resources iframe to the web page and make the request inside as it's the same as the background script. – wOxxOm Jan 13 '23 at 07:55
  • @wOxxOm thank you sooooo much! I actually was using the wrong way of importing my content script as outlined in the same thread that you shared. I swapped over to the method you suggested, and all the messaging works now! Before, I was injecting the content script into the page, and the messaging didnt work at all. Now it works :) – dataviews Jan 13 '23 at 14:46

0 Answers0