CORS issue during HTTP request from background service worker in Safari web extension - google-chrome-extension

Link to a repo with the Xcode project to test the issue: Test CORS Issue
This extension uses Manifest v3 and I have example.com in host_permissions
"host_permissions": [
"*://example.com/*"
]
When I run fetch("https://example.com") in background.js I get this error:
[Error] Fetch API cannot load https://example.com/ due to access control checks.
[Error] Failed to load resource: Origin safari-web-extension://e0b5d7c7-c079-484b-8825-44d261383cb6 is not allowed by Access-Control-Allow-Origin. Status code: 200 (example.com, line 0)
Tested in both Safari Version 16.0 (17614.1.25.9.10, 17614) and Safari Technology Preview Release 153 (Safari 16.0, WebKit 17615.1.4.1)
In the code I use chrome namespace (to test it in Chrome Browser) but I get the same issue with browser namespace.
If I run this extension without any change in Chrome Browser it works perfectly
(chrome://extensions/ → Load Unpacked)
Is there a way to avoid CORS issues without altering server access control settings?
Manifest v2 worked fine in this way.
Update 1:
The workaround for now to use background scripts (deprecated in v3) instead of background service worker.
Instead of this:
"background": {
"service_worker": "background.js"
},
Do this:
"background": {
"scripts": ["background.js"]
},
Update 2: How to make your extension work for both Chrome and Safari?
Chrome supports only
"background": {
"service_worker": "background.js"
},
Safari supports both service_worker and scripts but when you use service_worker it has this CORS issue.
So the solution is to ship extension with different values in background field.

Related

Chrome Extension Service worker registration failed. Status code: 2

I'm making a Chrome Extension (using manifest v3) but when I try to "Load Unpacked" I get an error and all it says is Service worker registration failed. Status code: 2. Any help would be much appreciated!
manifest.json
{
"name": "Test",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
}
}
background.js
console.log('MY SERVICE WORKER')
Probably doesn't matter but I'm on
Chrome Version 109.0.5414.87 (Official Build) (x86_64)
and macOS BigSur

Not able to import scripts inside service_worker js in chrome extension manifest version 3

I had multiple background scripts in chrome extension manifest version 2.
Now I need to migrate to manifest version 3 and therefore need to make necessary changes.
According to documentation, I have kept only one file in service_worker as shown below:
"background": {
"service_worker": "background.js"
},
and in the background.js I wrote the following javascript statement:
try {
importScripts('js/google-analytics.js', 'js/google-analytics-bundle.js', 'js/eventSender.js', 'js/api-gsc.js', 'js/api-sm.js', 'js/lib/jquery.js');
} catch (e) {
console.error(e);
}
The code in google-analytics.js has the following code:
window.onload = startApp;
Also, inside background.js I am using localStorage.
When I try to load the extension, it gives me the following errors:
background.js:16 ReferenceError: window is not defined
at google-analytics.js:23
at background.js:14
Error in event handler: ReferenceError: localStorage is not defined
at chrome-extension://<ExtensionId>/background.js:99:28
TypeError: Cannot read property 'createElement' of undefined
at ja (jquery.js:2)
at jquery.js:2
at jquery.js:2
at jquery.js:2
at jquery.js:2
at background.js:14
Error handling response: ReferenceError: XMLHttpRequest is not defined
at getUserStatus (chrome-extension://<extensionId>/js/api-gsc.js:9:19)
at chrome-extension://<ExtensionId>/background.js:112:17
and many other errors also.
It seems like it is not able to import the javaScript files properly.
It might be alot to ask in a single question. But, can someone please help me where I am putting wrong code and if someone please help me with the solution.
Thanks in advance.
try use fetch() replace XMLHttpRequest
I think you can find answer in this page Cross-origin XMLHttpRequest
For importing scripts in background js you need to bundle it seperate from the main app with imports specific to each if you are using vite as a bundler then you can add a package called as crxjs to manage content and background scripts
Follow the below steps to get your backgroud script running in vite
1.Add crxjs to your project
npm install #crxjs/vite-plugin -D
2.Add background js/ts
import xyz from "xyz"
// you can use package now
console.log(xyz)
3.Create or update manifest.json
{
"manifest_version": 3,
"name": "CRXJS React Vite Example",
"version": "1.0.0",
"action": { "default_popup": "index.html" },
"background": {
"service_worker": "background.js",
"type": "module"
},
}
4.Update your vite.config.ts file with path to manifest
import { defineConfig } from 'vite'
import react from '#vitejs/plugin-react'
import { crx } from '#crxjs/vite-plugin'
import manifest from './manifest.json'
export default defineConfig({
plugins: [
react(),
crx({ manifest }),
],
})
After this run your project , now config.js will be bundled and you can import packages in it

Chrome extension background script console.log() error

In my manifest I have this:
"background": {
"page": "background.html",
// "scripts": ["background.js"],
"persistent": true
},
Note that the background script is loaded from "background.html" because of some special reason I need to have that html page. This part of the manifest cannot be changed.
With this setting, the background script is working fine, but when I include a console.log("Succeed.") line, the script loads with an error, as follows:
Mysteriously, the logging actually worked and I could see it in the background.html's console.
But I could not get rid of the error, despite adding:
var console2 = chrome.extension.getBackgroundPage().console;
It's a relatively minor bug, as everything seems to work except there is an error message.

Using Dart in Chrome extension content script does not run?

I am trying to write a Chrome extension using Dart. So far everything goes well except for the content script --- the "main" function in the content script dart file does not seem to run.
To be more specific, first of all Dartium cannot be used since giving a dart file in the "js" rule in the manifest caused Dartium to complain; I next tried to compile the dart file (with csp: true) then make the manifest to include the compiled js file directly --- then I'm stuck, it seems that no matter what I try, the (compiled) "main" function just does not run.
Any suggestions?
Update:
The manifest file:
{
"manifest_version": 2,
"name": "Assistant",
"description": "Assists you with various tasks.",
"version": "1.0",
"minimum_chrome_version": "26.0",
"permissions": ["<all_urls>", "storage"],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": [
"packages/browser/dart.js",
"dart_content_script.dart.js"
],
"run_at": "document_start",
"all_frames": false
}
],
"browser_action": {
"default_popup": "popup.html",
"default_icon": "bulb.png"
},
"background": {
"page": "background.html"
}
}
The content script dart file:
void main() {
print('main done');
}
The pubspec.yaml:
name: AssistentExtension
dependencies:
browser: any
chrome: any
dev_dependencies:
unittest: '>=0.10.0'
transformers:
- $dart2js:
csp: true
In the Chrome developer console, I can find the string "main done" meaning that the "main" function is indeed included in the compiled js, but nothing is printed meaning it is not run.
I had the same problem like yours. At that time I looked into the console logs, a log saying chrome package is missing (but i don't know what cause it), so I manually added it back to build folder, then it worked so I can see my logs written in main().
When I run test_ext that come with official chrome pub, I get a different error message in console log, again I solved it and then the test_ext sample is running well too.
So, my advise is take a look at the console log, it might help. You can open console for extension by right click on popup UI of extension and select 'Inspect Element' to open it.

Why won't Chrome load extension with Content Security Policy that allows localhost?

I'm working on a Chrome extension and wanted to load scripts from localhost for development. So I updated the manifest file to have the following line:
"content_security_policy": "script-src 'self' http://localhost; object-src 'self'",
According to the doc on Content Security Policy, it's perfectly fine to use localhost or 127.0.0.1 without https.
However, I get the following (taunting) error message when I try to load the extension from chrome://chrome/extensions/:
Could not load extension from '/Users/Tim/Desktop/temp/test'. Invalid value for 'content_security_policy': Both 'script-src' and 'object-src' directives must be specified (either explicitly, or implicitly via 'default-src'), and both must whitelist only secure resources. You may include any of the following sources: "'self'", "'unsafe-eval'", "http://127.0.0.1", "http://localhost", or any "https://" or "chrome-extension://" origin. For more information, see http://developer.chrome.com/extensions/contentSecurityPolicy.html
To confirm the problem, you can create an empty directory with the following manifest.json file:
{
"name": "Example extension",
"description": "Trying to demonstrate a bug in Chrome",
"version": "0.1",
"homepage_url": "http://example.com",
"content_security_policy": "script-src 'self' http://localhost; object-src 'self'",
"manifest_version": 2
}
and load the directory as an unpacked extension. You should be getting the error. If you remove http://localhost or change it to https://localhost, it will load fine.
Am I missing something?
(NB: I'm using Chrome 22.0.1229.79)
Thanks!
The ability to add localhost to the CSP value was enabled by Chromium revision 151470, which is in Chrome 23 (currently in the dev channel, soon to be in the beta channel).

Resources