import IJS from 'image-js';
import { parse } from './mrz-relax';
export async function detectAndParseMrz(imageData, fs, result = {}, progress) {
// Initialize mrz-detection with provided filesystem
const { getMrz, readMrz } = await import('mrz-detection')({fs: fs});
...
Uncaught (in promise) TypeError: import() is disallowed on ServiceWorkerGlobalScope by the HTML specification. See
dist/detect-and-parse-mrz.bundle.js:2 (anonymous function)
Assistant
The error indicates that dynamicimport()statements are not allowed in a ServiceWorker context, such as the background script of a Chrome extension. This restriction is due to security concerns in the Service Worker API.
Here’s how you can resolve the issue:
1.Avoid Dynamicimport()in the Background Script
Replace the dynamicimport()with static imports, which are allowed in Service Workers.
javascriptCopy codeimport IJS from 'image-js';
import { parse } from './mrz-relax';
import { getMrz, readMrz } from 'mrz-detection';
export async function detectAndParseMrz(imageData, fs, result = {}, progress) {
// Use imported methods directly
}
This approach will bundle all necessary modules at build time, making them available to the background script.
2.Use a Dedicated Worker
If you need dynamic imports, move theimport()logic to aWeb Worker. You can communicate between the Service Worker and the Web Worker usingMessageChannel.
Example:
Web Worker (mrz-worker.js)javascriptCopy codeimportIJSfrom'image-js';import{ parse }from'./mrz-relax';const{ getMrz, readMrz } =awaitimport('mrz-detection');
javascriptCopy codeimport IJS from 'image-js';
import { parse } from './mrz-relax';
import { getMrz, readMrz } from 'mrz-detection';
4.Bundle the Code
Use a bundler like or Rollup to combine all modules into a single file. This will resolveimport()at build time, eliminating the need for dynamic imports.
By following one of these solutions, you can resolve the error and adapt your Chrome extension's background script for compatibility with the Service Worker environment.
Themrz-detectionmodule structure suggests thatreadMrzdepends on theoptionsargument passed when importing the module. If you're encountering issues due to this structure in a Service Worker, you can make adjustments depending on your approach:
Refactor to Static Imports
If you have control over themrz-detectionmodule, you can refactor it to allow for static imports without requiring a factory function. For example:
export async function detectAndParseMrz(imageData) {
const mrz = await getMrz(imageData);
const result = await readMrz(mrz);
return result;
}
This eliminates the need forimport()in the Service Worker context.
Use a Web Worker for Dynamic Loading
If modifyingmrz-detectionis not an option and you must keep the dynamic loading behavior, offload therequire()calls to a Web Worker. The Web Worker would handlemrz-detectionlogic, leaving the Service Worker to simply communicate with it.
Bundle Dependencies
Using a bundler like , you can preprocessrequire()calls during the build step. resolves these calls statically, ensuring compatibility with environments like Service Workers.
After this fix, got new error:
Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://:*".
Assistant
The error arises because your extension'sContent Security Policy (CSP)disallows the use ofeval()and similar constructs likeFunctionor dynamic code evaluation. This restriction is enforced by Chrome to improve security, especially for extensions.
Here’s how to address it:
Identify the Source ofeval
The error suggests that a library or part of your code is usingevalor similar constructs. Common culprits include:
Bundlers (e.g., Webpack, Rollup) that generate code usingeval.
Libraries that rely onevalinternally.
Bundlers (e.g., Webpack, Rollup) that generate code usingeval.
Libraries that rely onevalinternally.
To locate the source:
Search forevalin your codebase and dependencies.
Use debugging tools in the browser to inspect the error stack trace and identify the library or file causing the issue.
Search forevalin your codebase and dependencies.
Use debugging tools in the browser to inspect the error stack trace and identify the library or file causing the issue.
Adjust the Build Configuration
If you’re using a bundler like or Rollup, ensure that it does not generate code witheval.
Webpack Configuration:Set thedevtooloption to avoideval:javascriptCopy {devtool:'cheap-module-source-map',// Avoid 'eval'-based source maps// Other config...};
Rollup Configuration:Ensure no plugins introduceeval. Use plugins likerollup-plugin-terserto optimize the output.
Webpack Configuration:Set thedevtooloption to avoideval:
Rollup Configuration:Ensure no plugins introduceeval. Use plugins likerollup-plugin-terserto optimize the output.
Refactor Code to Avoideval
If the library useseval, check if it has a "CSP-compliant" version or a configuration option to disableeval. For example:
Some libraries provide an alternate build (e.g.,nodevsbrowserversions).
Replace or polyfill modules that rely oneval.
Some libraries provide an alternate build (e.g.,nodevsbrowserversions).
Replace or polyfill modules that rely oneval.
Modify the Content Security Policy (CSP)
If necessary and permissible, you can modify the CSP inmanifest.jsonto allowunsafe-eval. However,this approach is not recommendedunless you absolutely trust all code in your extension, as it weakens security.
If the source ofevalis Webpack, the issue is likely related to how generates code during the build process. Webpack usesevalin some configurations for performance reasons (e.g., in development mode). To fix this issue and make your extension CSP-compliant, you need to adjust the configuration.
Steps to FixevalIssues in Webpack
Change thedevtoolSetting
Thedevtoolsetting in determines how source maps are generated. Some configurations, likeevaloreval-source-map, rely oneval.
Update thewebpack.config.jsto use a CSP-compliant source map:
javascriptCopy codemodule.exports = {
mode: 'production', // Enables optimizations and disables eval-like features
// or
mode: 'development', // For development builds
};
CSP-Compatible Loader Settings
If you are using loaders (e.g., Babel, TypeScript, etc.), ensure that their configurations do not introduceeval. For example, configure Babel to avoid dynamic code generation.
Service worker registration failed. Status code: 15
{
"manifest_version": 3,
"name": "Visaif - Visa Application Assistant",
"version": "1.0.1",
"description": "AI-powered visa application assistant with Singapore Arrival Card autofill support",
"permissions": [
"activeTab",
"storage",
"scripting",
"tabs"
],
"host_permissions": [
],
"action": {
"default_popup": "popup/index.html",
"default_icon": {
"16": "assets/icon16.png",
"48": "assets/icon48.png",
"128": "assets/icon128.png"
}
},
"icons": {
"16": "assets/icon16.png",
"48": "assets/icon48.png",
"128": "assets/icon128.png"
},
"background": {
"service_worker": "scripts/background.mjs",
"type": "module"
},
"content_scripts": [
{
"matches": [],
"js": [
"scripts/content.js",
"scripts/form-filler.js"
],
"css": ["styles/content.css"]
}
],
"web_accessible_resources": [{
"resources": [
"assets/",
"scripts/"
],
"matches": []
}]
}
Uncaught EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval' 'inline-speculation-rules' http://localhost:* http://:*".
Context
dist/detect-and-parse-mrz.bundle.js
Stack Trace
dist/detect-and-parse-mrz.bundle.js:2 (anonymous function)
1
2
/*! For license information please see detect-and-parse-mrz.bundle.js.LICENSE.txt */
Assistant
The error arises from Webpack's bundling ofdist/detect-and-parse-mrz.bundle.js, which still introduces CSP violations (evalor similar constructs). Here's a structured approach to resolve the issue:
Address the Root Cause in Webpack
The issue originates from Webpack's handling of the bundle. You need to ensure that avoids generating any code that usesevalor similar constructs.
Update Webpack Configuration
Ensure that Webpack's configuration disablesevaland related features entirely:
devtool:Choose a CSP-compliant option for source maps:javascriptCopy codedevtool:'source-map',// CSP-compliant (use in production)
Some dependencies might includeevalor similar constructs in their code. You can:
Inspect dependencies for CSP compliance.
Replace problematic libraries with CSP-compliant alternatives.
Inspect dependencies for CSP compliance.
Replace problematic libraries with CSP-compliant alternatives.
WebpackexternalsConfiguration
If a dependency is introducing the issue, you can mark it as an external and load it differently (e.g., via CDN):
User
how to change browser Content Security Policy for personal usage?
Assistant
Changing the Content Security Policy (CSP) of a browser for personal use is not straightforward, as modern browsers enforce CSP to improve security. However, for personal use or testing purposes, there are some workarounds you can use to modify or bypass CSP.
Here are the options:
Use a Chrome Extension to Override CSP
You can create or use an existing Chrome extension to override the CSP for specific websites.
By applying one of these solutions, you can adaptmrz-detectionfor use in a Service Worker without encountering issues from therequire()orimport()calls.
⚠️Caution:Using'unsafe-eval'is a security risk and will likely lead to rejection if publishing your extension to the Chrome Web Store. Only use this in local development or trusted environments.
Replace Problematic Dependencies
If the library you're using cannot work withoutevaland has no workaround, consider replacing it with an alternative library that is CSP-compliant.
For example:
Ifevalis used inmrz-detection, check for other MRZ detection libraries or rewrite portions of the logic to remove dynamic code evaluation.
Ifevalis used inmrz-detection, check for other MRZ detection libraries or rewrite portions of the logic to remove dynamic code evaluation.
Debugging in Local Development
If the CSP issue arises only in development (e.g., due to localhost permissions), ensure that your testing environment matches production as closely as possible.
Use consistent CSP rules between development and production.
Avoid relying on localhost-specific rules unless necessary.
Use consistent CSP rules between development and production.
Avoid relying on localhost-specific rules unless necessary.
Conclusion
The best approach depends on the source ofeval:
Avoidevalby refactoring the code or replacing the dependency.
Ensure your build process generates CSP-compliant output.
As a last resort, adjust the CSP, but avoidunsafe-evalin production environments.
Avoidevalby refactoring the code or replacing the dependency.
Ensure your build process generates CSP-compliant output.
As a last resort, adjust the CSP, but avoidunsafe-evalin production environments.
If your extension uses , ensure it's correctly configured for environments like Service Workers:
javascriptCopy codeoutput: {
globalObject: 'self', // Ensures compatibility with Service Workers
},
Rebuild the Extension
After making the changes, rebuild the extension and verify that related CSP issues remain. Use tools like Chrome DevTools to inspect the compiled bundle for compliance.
⚠️Warning:This disables all security protections like CORS and CSP. Use this only in isolated environments or for testing purposes.
Firefox:
Go toabout:config.
Search forsecurity.csp.enableand set it tofalse.
Go toabout:config.
Search forsecurity.csp.enableand set it tofalse.
⚠️ Disabling CSP in Firefox can make your browsing session vulnerable. Use it only in a testing context.
Use a Proxy Tool to Modify HTTP Responses
You can use a proxy tool likeFiddler,, orBurp intercept and modify HTTP responses to strip or adjust CSP headers.
Example with Fiddler:
Open Fiddler and enable "Capture Traffic."
Use a script to remove or modify theContent-Security-Policyheader:Go to and selectCustomize Rules.Add the following script:csharpCopy codestaticfunctionOnBeforeResponse(oSession: Session) {
oSession.oResponse["Content-Security-Policy"] =null;
}
Go to and selectCustomize Rules.
Add the following script:csharpCopy codestaticfunctionOnBeforeResponse(oSession: Session) {
oSession.oResponse["Content-Security-Policy"] =null;
}
Save the script and browse through the proxy.
Open Fiddler and enable "Capture Traffic."
Use a script to remove or modify theContent-Security-Policyheader:
Go to and selectCustomize Rules.
Add the following script:csharpCopy codestaticfunctionOnBeforeResponse(oSession: Session) {
oSession.oResponse["Content-Security-Policy"] =null;
}
csharpCopy codestatic function OnBeforeResponse(oSession: Session) {
oSession.oResponse["Content-Security-Policy"] = null;
}
Save the script and browse through the proxy.
Modify CSP in Developer Tools (Temporary Change)
You can temporarily bypass CSP using the browser's developer tools:
Open Developer Tools (F12).
Go to theNetworktab.
Select a specific request, right-click, and chooseCopy as cURL.
Use a tool likecurlor an intercepting proxy to manually modify and resend the request without CSP headers.
Open Developer Tools (F12).
Go to theNetworktab.
Select a specific request, right-click, and chooseCopy as cURL.
Use a tool likecurlor an intercepting proxy to manually modify and resend the request without CSP headers.
Use a Custom Browser Build
For complete control over CSP behavior, you can build a custom version of an open-source browser like Chromium or Firefox. Modify the CSP enforcement in the browser's source code.