Chrome extension background script console.log() error - google-chrome-extension

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.

Related

CORS issue during HTTP request from background service worker in Safari web 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.

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

Content script pattern "*://mail.google.com/*" doesn't match gmail when using firefox

I have an extension that I've written for chrome. I recently decided I wanted to port it over to firefox, and I was surprised on how many things worked out of the box with no changes at all. However, one thing that has tripped me up is that for some reason my gmail.js content script is not being loaded. This is my content script:
{
"name": "Copy Machine",
"description": "Copies text more better",
"version": "0.6",
"permissions": ["contextMenus", "tabs"],
"icons": {
"16": "icon_16.png",
"32": "icon_32.png"
},
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"*://mail.google.com/*"
],
"js": ["gmail.js"],
"run_at": "document_idle"
},
{
"matches": [
"<all_urls>"
],
"js": ["generic.js"],
"run_at": "document_idle"
}
]
}
The first line of my gmail.js content script is:
console.log("GMAIL SCRIPT IS RUNNING");
And the first line of my generic.js content script is:
console.log("GENERIC SCRIPT IS RUNNING");
When I open my gmail account in firefox, in the console I see "GENERIC SCRIPT IS RUNNING", but not "GMAIL SCRIPT IS RUNNING."
With google chrome, this works as I would expect, but for some reason the URL pattern isn't matching. Is there something I am missing? Thanks.
So I ended up adding "*://mail.google.com/*" to the permissions in the manifest file, and that got things working the way I expected. I then had to fix a few other bugs with apis that were not available, this is what I should have started with:
https://extensionworkshop.com/documentation/develop/porting-a-google-chrome-extension/
I then went back to file a bug report, and when I remove "*://mail.google.com/*" it's continues to work. So maybe there's some weird circular dependency thing going on? I'm not sure.

Why is my content script file loaded as an empty file?

I'm creating a Chrome extension which inserts a content script, but the content script appears to be loaded as an empty file.
manifest.json
{
"manifest_version": 2,
"name": "Test",
"content_scripts": [
{
"matches": ["http://stackoverflow.com/*"],
"js": ["content_script.js"]
}
]
}
content_script.js
console.log('hello world');
When I go to chrome-extension://<extension's id>/content_script.js, I see the correct content of console.log('hello world');, but in the browser it appears empty:
And nothing is printed to the console. Does anyone know what can cause this?
Also, I tried adding some more files and folders. All the files and folders appear in the sources tab, but all the files are empty.
I had the same issue. In my case, the reason Chrome refused to read content.js is that the file was an alias (I was using ln -s). Copy the original file to the extension folder solved the issue for me.
Saw that too a few times on Chrome dev channel, it started a few months ago, obviously a bug.
Try restarting the browser.
Try adding debugger; in the code.
Try specifying "run_at": "document_start" (or document_end) in the content script declaration.

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.

Resources