Chrome extension MV3 doesn't work with Vite server? - google-chrome-extension

I'm trying to create a Chrome Extension with Vite and HMR.
My Vite configuration for Popup only...
base: isServer ? 'https://localhost:3303/' : './',
server: {
port: 3303,
hmr: {
host: 'localhost'
}
},
build: {
sourcemap: isDevelopment ? 'inline' : false,
outDir: path.resolve('dist/'),
emptyOutDir: false,
terserOptions: {
mangle: false
},
rollupOptions: {
input: {
index: path.resolve(pagesDirectory, 'popup', 'index.html')
},
output: {
sourcemap: true,
entryFileNames: 'src/pages/[name]/index.js',
chunkFileNames: isDevelopment ? 'assets/js/[name].js' : 'assets/js/[name].[hash].js',
assetFileNames: (assetInfo) => {
const { dir, name: _name } = path.parse(assetInfo.name);
const assetFolder = getLastElement(dir.split('/'));
const name = assetFolder + firstUpperCase(_name);
return `assets/[ext]/${name}.chunk.[ext]`;
}
}
}
... // Other configuration
And this results on this HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no, viewport-fit=cover" />
<link rel="preconnect" href="//firebaseinstallations.googleapis.com">
<link rel="preconnect" href="//firebaseremoteconfig.googleapis.com">
<link rel="preconnect" href="//firebaselogging-pa.googleapis.com">
<title>Popup</title>
</head>
<body>
<div id="app-container">Vite server did not start</div>
<script type="module" src="http://localhost:3303/popup/index.tsx"></script>
</body>
</html>
My manifest
{
"manifest_version": 3,
"background": {
"service_worker": "src/pages/background/background.global.js"
},
"permissions": [
"tabs",
"webNavigation"
],
"host_permissions": [
"http://*/*",
"https://*/*",
"http://localhost:3303/*"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; default-src 'self'; object-src 'self'"
},
"content_scripts": [
{
"matches": [
"https://*.google.com/search?q*"
],
"css": [
"src/pages/contentScript/style.css"
],
"js": [
"src/pages/contentScript/contentScript.global.js"
]
}
],
"action": {
"default_title": "Web Answers",
"default_popup": "src/pages/popup/index.html"
},
"web_accessible_resources": [
{
"resources": [
"assets/js/**/*"
],
"matches": [
"<all_urls>"
]
},
{
"resources": [
"src/pages/**/*.js.map"
],
"matches": [
"<all_urls>"
]
},
{
"resources": [
"src/pages/**/*.css"
],
"matches": [
"<all_urls>"
]
},
{
"resources": [
"locales/*"
],
"matches": [
"<all_urls>"
]
}
],
}
Error
With this configuration, I'm getting this error
Vite server did not start
Second attempt
In the manifest, I included http://localhost:3303 into extension_pages...
...
"content_security_policy": {
"extension_pages": "script-src 'self' 'http://localhost:3303'; default-src 'self'; object-src 'self'"
},
...
'content_security_policy.extension_pages': Insecure CSP value "'http://localhost:3303'" in directive 'script-src'.
Could not load manifest.

Related

Chrome Extension MV3: Uncaught ReferenceError: Worker is not defined

I am trying to convert from MV2 to MV3 and I am getting this error from the service worker error logs:
Service worker registration failed
Uncaught ReferenceError: Worker is not defined
Here is my MV3 settings:
`{
"manifest_version": 3,
"name": "Blah",
"description": "Blah",
"version": "1.0.0",
"minimum_chrome_version": "93",
"action": {
"default_icon": "logo.png",
"default_popup": "popup.html"
},
"background": {
"service_worker": "js/background.js"
},
"content_scripts": [
{
"matches": ["file://*/*", "http://*/*", "https://*/*"],
"js": ["js/content.js"],
"run_at": "document_start",
"all_frames": true
}
],
"icons": {
"16": "icon-16.png",
"48": "icon-48.png",
"128": "icon-128.png"
},
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'; worker-src 'self'"
},
"permissions": [
"scripting",
"clipboardWrite",
"tabs",
"activeTab",
"notifications",
"webRequest",
"proxy",
"storage",
"unlimitedStorage",
"alarms"
],
"host_permissions": [
"http://*/",
"https://*/",
"<all_urls>"
],
"web_accessible_resources": [
{
"resources": ["js/injected.js"],
"matches": ["*://*/*"]
}
]
}`
And here is the backgound script:
import { browser } from "webextension-polyfill-ts";
import { Request } from "#src/types";
import Extension from "./extension";
const app: Extension = new Extension();
try {
app.initialize().then(async () => {
// eslint-disable-next-line #typescript-eslint/no-unused-vars
browser.runtime.onMessage.addListener(async (request: Request, _) => {
try {
const res = await app.handle(request);
return [null, res];
} catch (e: any) {
return [e.message, null];
}
});
} catch (error) {
console.log("Error in backgound!!1");
}
Is there any missing configs in the background script or the MV3 json file?
It is an old bug when using nested web-worker with chrome extensions which is not supported yet: https://bugs.chromium.org/p/chromium/issues/detail?id=31666
I found the solution here: https://stackoverflow.com/a/33991381/9058556
It was simply installing https://github.com/dmihal/Subworkers package and importing it in my background.js script at the top.
Thanks #norio-yamamoto for trying to help me with this.

Chrome Extension - declarativeNetRequest remove requestHeader "origin" not working

I am trying to remove requestHeader 'origin' using declarativeNetRequest. It's not working as the origin is still being sent with SharePoint rest api call. How do we ensure the rule is being triggered or not? How can we troubleshoot the issue?
Here is my manifest.json and rules.json
{
"short_name": "SPO Helper",
"name": "SPO Helper",
"icons": {
"16": "favicon.ico",
"48": "logo192.png",
"128": "logo512.png"
},
"manifest_version": 3,
"version": "0.0.1",
"background": {
"service_worker": "./static/js/background.js"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"content.js"
],
"all_frames": false,
"run_at": "document_end"
}
],
"action": {
"default_title": "SPO Helper"
},
"declarative_net_request": {
"rule_resources": [
{
"id": "ruleset_1",
"enabled": true,
"path": "./rules.json"
}
]
},
"permissions": [
"tabs",
"activeTab",
"cookies",
"scripting",
"declarativeNetRequest",
"declarativeNetRequestFeedback"
],
"host_permissions": [
"https://*.sharepoint.com/"
],
"content_security_policy": {
"extension_pages": "script-src 'self'; object-src 'self'"
}
}
rules.json
[
{
"id": 1,
"priority": 1,
"action": {
"type": "modifyHeaders",
"requestHeaders": [
{
"header": "origin",
"operation": "remove"
}
]
},
"condition" : {
"domains": ["cbgbfoeehbjllcimibeojmpgeoncgjcl"],
"resourceTypes" : ["main_frame", "sub_frame"]
}
}
]
using onRuleMatchedDebug you can check if your rule is being triggered.
you must add the declarativeNetRequestFeedback permission in your manifest.json and add this in your service worker:
chrome.declarativeNetRequest.onRuleMatchedDebug.addListener(function (o) {
console.log('rule matched:', o);
});

chrome.tabs.executeScript not working on amazon.com

the callback function never get called on amazon product pages, eg:
https://www.amazon.com/AmazonBasics-0188-3-PACK-Multipurpose-Scissors/dp/B01BRGU8R0/ref=sr_1_13?dchild=1&keywords=amazonbasics&pf_rd_p=9349ffb9-3aaa-476f-8532-6a4a5c3da3e7&pf_rd_r=14VHDM69CE2KAX6H70ED&qid=1596591703&sr=8-13
chrome.tabs.executeScript(tabId,
{
code: script,
allFrames: true,
},
function (result) {
console.log('run script result:', result);
sendReplyToQuicker(true, "", result, msg.serial);
})
as simple as only one line code will not getting result:
1;
When run this code on other site:
When run this code on amazon page, callback function nerver called:
The extension manifest.json (full code):
{
"name": "Quicker Chrome Connector",
"version": "0.3.1",
"manifest_version": 2,
"description": "Native message connector with Quicker application",
"background": {
"scripts": [
"main.js"
],
"persistent": false
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"jquery-3.5.1.min.js",
"content.js"
],
"all_frames": true
}
],
"icons": {
"128": "icon-128.png"
},
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"nativeMessaging",
"tabs",
"<all_urls>",
"debugger"
],
"optional_permissions":[
"bookmarks",
"browsingData",
"topSites",
"downloads",
"history",
"pageCapture",
"cookies",
"sessions",
"management"
],
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"homepage_url": "https://getquicker.net"
}

TypeError: Cannot read property 'farewell' of undefined

I have a problem while making a chrome extension. It gives me an error "TypeError: Cannot read property 'farewell' of undefined". I was doing it by Chrome documentation.
Background script:
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
Content script:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello") sendResponse({farewell: "goodbye"});
});
Manifest:
{
"name": "Test",
"version": "0.0.1",
"description": "Test app",
"permissions": [ "background", "tts", "storage", "webNavigation", "activeTab", "tabs" ],
"background": { "scripts": ["my.js"] },
"browser_action": {
"default_popup": "my.html"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"content_security_policy": "script-src 'self' http://localhost; object-src 'self'",
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"css": ["mystyles.css"],
"js": ["autofill.js", "smart.js"]
}
],
"manifest_version": 2
}

Why isn't my chrome extension working?

I've spent hours and hours trying to figure out what's wrong with my chrome extension. I know that my function.js code is good because it works with an html page that I link it to, but perhaps it isn't right for chrome extensions?
All help is appreciated
manifest.json
{
"manifest_version": 2,
"name": "Font Find",
"description": "This extension allows you to click on any text, and find out what font it is written in.",
"version": "1.0",
"background": {
"page": "popup.html",
"persistent": true
},
"permissions": [
"activeTab",
"http://*/*",
"https://*/*"
],
"browser_action": {
"default_title": "Find the Font",
"default_icon": "icon.png"//,
// "default_popup": "popup.html"
},
"background": { "scripts": ["jquery.min.js"] },
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": [
"function.js"
]
}
]
}
popup.html file (note it isn't set as the popup)
<!DOCTYPE HTML>
<html>
<head>
<!-- <link rel="stylesheet" href="popup.css"/> -->
<script src="jquery.min.js"></script>
<script src="popup.js"></script>
<script src="function.js"></script>
</head>
</html>
function.js file
"use strict";
$("body").append('Test');
document.body.ondblclick = function(event){
//event.stopPropagation();
var target = event.target || event.srcElement;
alert( "What you clicked on:" + $(target).text() + " It's font-family is: " + $(target).attr("font-family") );
}
function.js file
chrome.browserAction.onClicked.addListener(function (tab) {
chrome.tabs.executeScript({
file: "function.js"
});
});
First, edit the manifest.json file. Add this code:
"content_scripts": [{
"matches": [
"http://*/*",
"https://*/*"
], "js": [
"jquery.min.js",
"function.js"
], "run_at": "document_start"
}]
And now, use this code in function.js file.
document.addEventListener("DOMContentLoaded", function() {
document.body.addEventListener("dblclick", function(e) {
var target = e.target;
alert("What you clicked on: " + $(target).text() + " It's font-family is: " + $(target).attr("font-family"));
}, true);
});
I tested this code and it works. I hope it helps.

Resources