Required module doesn't work on chrome extension script - node.js

I'm new to extension development and not good at bundlers so I'm using chrome-extension-webpack-boilerplate to start developing my extension.
I want to make a simple timer extension, so after following the bolirplate repository's instructions, I downloaded a module called tiny-timer with yarn add tiny-timer. Then changed the popup.html and popup.js (added code from the tiny-timer repo that works fine on RunKit).
manifest.json:
{
"name": "Chrome Timer Extension",
"options_page": "options.html",
"background": {
"page": "background.html"
},
"browser_action": {
"default_popup": "popup.html",
"default_icon": "icon-34.png"
},
"icons": {
"128": "icon-128.png"
},
"manifest_version": 2,
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
popup.js
import "../css/popup.css";
const Timer = require("tiny-timer");
console.log(Timer);
const timer = new Timer();
popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1 id="timer"></h1>
<button id="pause">Pause</button>
<button id="reset">Reset</button>
<button id="continue">Go</button>
</body>
</html>
Popup output:
Module
>default: class Timer
Symbol(Symbol.toStringTag): "Module"
__esModule: true
>[[Prototype]]: Object
Uncaught TypeError: Timer is not a constructor
at eval (popup.js?dffe:3)
at Module../src/js/popup.js (popup.bundle.js:1271)
at __webpack_require__ (popup.bundle.js:727)
at fn (popup.bundle.js:101)
at Object.0 (popup.bundle.js:1286)
at __webpack_require__ (popup.bundle.js:727)
at popup.bundle.js:794
at popup.bundle.js:797

Related

Using Mocked Service Worker (msw) with #web/test-runner

I am trying to setup msw with #web/test-runner (and playwright). The problem is that I don't know how the mockServiceWorker.js can be picked up by the test runner (which uses browser, not nodejs like jest). There is an example with karma:
https://github.com/mswjs/examples/tree/master/examples/with-karma, probably I have to do something similar but I have no idea where to start. Any hints are welcome.
I am not sure if it is important, but let me share my web.test-runner.config.js
import vite from 'vite-web-test-runner-plugin'
import { playwrightLauncher } from '#web/test-runner-playwright';
export default {
plugins: [ vite() ],
coverageConfig: {
include: [ 'src/**/*.{svelte,js,jsx,ts,tsx}' ]
},
browsers: [
playwrightLauncher({ product: 'chromium' })
],
testRunnerHtml: testFramework => `
<!DOCTYPE html>
<html>
<head>
<script type="module">
window.global = window;
window.process = { env: {} };
</script>
<script type="module" src="${testFramework}"></script>
</head>
</html>
};
and my test command
"test": "web-test-runner \"test/**/*.test.ts\"",

importScripts while error thrown from one of the script

In my chrome extension (manifest V3) I want to import some scripts like jquery and more.
Inside my backgound.js I have:
try {
importScripts('/js/jquery-3.4.1.min.js', '/js/common.js');
} catch (e) {
console.error('importScripts: ' + e);
}
...
calling to getCookie...
inside common.js I have function like:
async function getCookie(key) {
return ...;
}
but when I load the extension I get the error:
background.js:22 importScripts: TypeError: Cannot read property 'createElement' of undefined
This error comes from the Jquery library
and after I get another error:
Uncaught (in promise) ReferenceError: getCookie is not defined
because the error in jquery it doesn't load the common script? how can I fix that?
Is there a more stable solution to import the scripts? so that error in one script will not cause a fail to other scripts?
Posting the working solution for me: import the scripts from npm into background service worker:
In my manifest.json adding "type": "module" to my background script:
"background": {"service_worker": "background.js" , "type":"module"}
Inside my background.js simply importing desired module script:
import Dexie from "/node_modules/dexie/dist/modern/dexie.min.mjs"
REMAKRS:
Please notice that from Manifest Version 3 in order to invoke script into web-page from your background service workers you need to use chrome.scripting.executeScript. Example:
//background.js
let [tab] = await chrome.tabs.query({active: true, currentWindow: true})
//invoke function
await chrome.scripting.executeScript({
target: {tabId: tab.id},
function: colorSelectedText,
args: [tab.title]
})
});
//OR
//invoke file
await chrome.scripting.executeScript({
target: {tabId: tab.id},
files: ['your_script.js']
})
});
Desirable scripts must be in same parent folder as your manifest.json (wasn't working when I was trying to use two dots ../path)
You can package your extension application with the version of jquery you would like to use . then you add it as part of your service workers. This is how my manifest.json looks like
{
"name": "Foo Bar",
"description": "NA",
"version": "1.0",
"manifest_version": 3,
"permissions": [
"storage"
],
"action": {
"default_popup": "popup.html"
},
"background": { "service_workers": ["bg-loader.js","/js/jquery-3.6.0.min.js" ]}
}
I have a bg-loader.js which i use to import my js logic script where i have my jquery functions
try {
importScripts('/js/index.js' /*, and so on */);
} catch (e) {
console.error(e);
}
Then in my index.html i add my jquery script to my popup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>test</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
</body>
<script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</html>

Process is not defined for Electron's Getting Started App [duplicate]

This question already has answers here:
Unable to use Node.js APIs in renderer process
(2 answers)
Closed 1 year ago.
I am trying to get started with Electron. I was already able to run all simple examples. They all work as expected. When I try to follow the Quick Start Guide I experience the same issue as mentioned in this question: The app launches properly, but does not display the versions of node Chrome and Electron. When I look into the developing tools I see this error:
Uncaught ReferenceError: process is not defined
at index.html:14
However, I have set nodeIntegration to true.
Why is it still not working?
Versions:
npm 7.6.3
node v14.16.0
chromium 89.0.4389.82
Operating System:
Ubuntu 20.04.2 LTS.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello World!</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline';" />
</head>
<body style="background: white;">
<h1>Hello World!</h1>
<p>
We are using node
<script>document.write(process.versions.node)</script>,
Chrome
<script>document.write(process.versions.chrome)</script>,
and Electron
<script>document.write(process.versions.electron)</script>.
</p>
</body>
</html>
main.js
const { app, BrowserWindow } = require('electron')
function createWindow () {
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true
}
})
win.loadFile('index.html')
}
app.whenReady().then(createWindow)
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit()
}
})
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow()
}
})
package.json
{
"name": "my-electron-app",
"version": "0.1.0",
"author": "username",
"description": "My Electron app",
"main": "main.js",
"scripts": {
"start": "electron ."
},
"devDependencies": {
"electron": "^12.0.0"
}
}
Try to set this value when creating your BrowserWindow:
webPreferences: { nodeIntegration: true, contextIsolation: false }
A new major Electron version has been released which broke the tutorial.
The specific breaking change is a new default value of contextIsolation flag.
For more details, see this GitHub issue.

Writing subscript in Mathjax?

I want to type this .
I have tried like this
$$\lambda=\frac{0.693}{t_\frac{1}{2}}$$
Also,
$$\lambda=\frac{0.693}{{t}_\frac{1}{2}}$$
Also,
$$\lambda=\frac{0.693}{t_{\frac{1}{2}}}$$
But it don't work it display something like this
This code
also gives something that we don't want
Mathjax Configuration
<div class="layout"><script type="text/x-mathjax-config">
MathJax.Hub.Config({
TeX: {extensions: ["AMSmath.js","AMSsymbols.js","mhchem.js","noErrors.js","noUndefined.js"]},
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ],
processEscapes: true
},
});
</script>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
Browser= Google Chrome
OS= Windows 8.1
Use _{}
_{YOUR EXPRESSION}
Example:
$$Y_n = Y_{n-1}+{{(d/n)}sin(θ\pm n*Δ)}.$$
Result:
$$\frac{1}{\lambda}=\frac{0.693}{t_\frac{1}{2}}$$
renders exactly what you are asking for and I tested it already.
Note the difference:
I just copied your first mathjax code:
$$\lambda=\frac{0.693}{t_\frac{1}{2}}$$
Note that before the '=' on the left side of the equation you just and simply wrote \lambda and that was your only mistake, so I simply replaced \lambda with \frac{1}{\lambda} and that's all.
You already showed us in your question that you already know that underscore _ renders subscript text and symbols in mathjax by the way.
See the live example below:
window.MathJax = {
config: ["MMLorHTML.js"],
jax: ["input/TeX", "input/MathML", "input/AsciiMath", "output/HTML-CSS", "output/NativeMML"],
extensions: ["tex2jax.js", "mml2jax.js", "asciimath2jax.js", "MathMenu.js", "MathZoom.js"],
asciimath2jax: {
delimiters: [
['`', '`'],
['$', '$']
]
},
TeX: {
extensions: ["AMSmath.js", "AMSsymbols.js", "noErrors.js", "noUndefined.js"]
},
tex2jax: {
inlineMath: [
['$', '$'],
["\\(", "\\)"]
],
processEscapes: true
}
};
.MathJax_CHTML {
font-size: 30px !important;
}
<script type="text/javascript" async src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML">
</script>
<p> $$\frac{1}{\lambda}=\frac{0.693}{t_\frac{1}{2}}$$</p>
<p> $$\frac{1}{\lambda}=\frac{0.693}{{t}_\frac{1}{2}}$$</p>
<p> $$\frac{1}{\lambda}=\frac{0.693}{t_{\frac{1}{2}}}$$</p>

How do I use YUI3 in a Chrome extension?

If I download the minified YUI3 loader and include it in my background.html I get the following 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' chrome-extension-resource:".
Can YUI3 be used in an extension?
It looks like it's blocking you from using eval(). Make sure you have the following line in your manifest.
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
This is how I was able to do it. Clone yui3 and yui3-gallery from git and in my extension tree, add the modules I need. Then load config.js from popup.html and background.html. The file looks like this:
YUI_config = {
filter: "raw",
base: "yui3/build/",
root: "yui3/build/",
comboBase: "/combo?",
combine: false,
groups: {
gallery: {
base: "yui3-gallery/build/",
root: "yui3-gallery/build/",
comboBase: "/combo?",
combine: false,
patterns: {
"gallery-": {},
"gallerycss-": { type: "css" }
}
}
}
};
Now it all works!

Resources