2

Yes, there is a similar question to this already has already been answered (Chrome Extension Socket io node js); however, it only works for background scripts (from what I've seen). So, how would I do this in the content script?

Here is what I have so far:

// manifest.json
// And yes, I've also tried to import "socket.io.js" as a background script

"content_scripts":
[
  {
    "matches": ["<all_urls>"],
    "js": ["socket.io.js", "index.js"]
  }
]
// index.js

const socket = io('http://localhost:8080');

socket.on('some-event', (data) => {
  ...
};

//  index.js:1 Uncaught ReferenceError: io is not defined
//    at index.js:1

What am I doing wrong?

Thanks.

Plot
  • 31
  • 7
  • 2
    You can't. Modern Chrome doesn't allow cross-origin requests in the content script. See [How to stop CORB from blocking requests to data resources that respond with CORS headers?](https://stackoverflow.com/a/55292071) – wOxxOm Sep 23 '20 at 11:48
  • A workaround is to add an extension frame in the current tab. That frame will be able to do everything the background script can. Look for examples of using extension iframes with web_accessible_resources. – wOxxOm Sep 23 '20 at 11:49
  • @wOxxOm Hi, should this still work? I just tried and got CORS error. Injected the iframe via content script with src being a local extension page. – yegorchik Jul 04 '22 at 15:15
  • @wOxxOm Actually, I'm a bit wrong. It looks like it's a http/https issue. Tried opening a website with http protocal and everything worked. Is there a workaround for this while I'm on a testing field? So that I won't need to get a domain/server/certificate while I'm developing. Also, if there will be another case, where my server will have https and the url I'm on will have http - that would cause a problem again? Does that mean I have to pass the protocol from the current page to the iframe and use a proper protocol for doing requests/establishing socket connection? – yegorchik Jul 04 '22 at 15:41

0 Answers0