How to use background.html in manifest v3 in chrome extension - javascript

I'm trying to use the library of ffmpeg.wasm to download m3u8 videos in the background.js but it shows the error
ffmpeg.js:1 Uncaught (in promise) ReferenceError: document is not defined
at ffmpeg.js:1
at ffmpeg.js:1
at f (ffmpeg.js:1)
at Generator._invoke (ffmpeg.js:1)
at Generator.next (ffmpeg.js:1)
at n (ffmpeg.js:1)
at c (ffmpeg.js:1)
at ffmpeg.js:1
at new Promise (<anonymous>)
at ffmpeg.js:1
After I checked the document, it suggested me to use jsdom or create a new tab or window.
Service workers do not have access to windows or the DOM. If your
extension needs that, you can use libraries like jsdom or use
chrome.windows.create and chrome.tabs.create. It depends on your usage
and what fits your needs.
This is also needed if your background scripts record audio or video,
as that is not possible in service workers.
However, the document did not actually teach me how to do. I tried to use chrome.windows.create and chrome.tabs.create but it is not what I want because it actually create a new window or tab explicitly.
Then, I tried to use jsdom. I installed it with NPM. After I imported the library, it showed the error
service worker registration failed
Here is my manifest.json:
{
"name": "vDonwloader",
"description": "Download HLS videos.",
"version": "1.0",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"action": {
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"],
"run_at": "document_start"
}
],
"permissions": [
"webRequest",
"tabs"
],
"host_permissions":[
"<all_urls>"
]
}
Here is my background.js:
importScripts('ffmpeg.js');
const { createFFmpeg, fetchFile } = FFmpeg;
const downloadHlsListener = async (msg, sender, sendResponse) => {
if(msg.action === 'DOWNLOAD_HLS'){
//...Do something
}
}
chrome.runtime.onMessage.addListener(downloadHlsListener);
How can I solve this problem? I want to make a chrome extension to download .m3u8 videos with ffempeg library.

Related

Chrome extension service workers stops listening to events after opening popup

I'm developing a chrome extension with MV3.
I've encountered an issue in which when I open the popup when clicking on the extension's icon the service worker background script stops receiving the chrome.tabs.onUpdated events, even after I close the popup. The only way I can make it work again is by reloading the extension.
I will mention that the popup that I'm rendering is a react app, not sure if it has to do with the issue, but when I swap the popup content to a normal HTML with just a button or something it is working as expected
Basically what I'm trying to do in the extension is listen to chrome.tabs.onUpdated event to detect URL changes in the background script, and send a message to a content script in order to save some data to the chrome local storage.
This is the manifest.json -
{
"name": "My Extension",
"description": "Extension POC",
"version": "0.0.0.1",
"manifest_version": 3,
"background": {
"service_worker": "background.js"
},
"permissions": ["tabs", "storage", "activeTab"],
"action": {
"default_popup": "build\\index.html",
"default_title": "Open Pane",
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
}
And this is the background.js -
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (!isPageDoneLoading(changeInfo)) {
return;
}
const url = tab.url;
const ticketId = url.substring(url.lastIndexOf("/") + 1);
if (isTargetURL(url) && !isNaN(ticketId)) {
// Update the ID only if it doesn't equal to the previous one or if null
if (!CURRENT_TICKET_ID || CURRENT_TICKET_ID !== ticketId) {
CURRENT_TICKET_ID = ticketId;
const props = getProperties(ticketId);
chrome.tabs.sendMessage(tabId, { action: {ticketId, props: props} });
}
}
})
Any idea what may be the root cause or how can I resolve the issue?
What React version are you using? In the older React version, part of the create-react-app script creates a file called serviceWorker.js. and a call to it in index.js. When I created a new project with a newer React version, 18.X.X it didn't create this file. I suppose there is some conflict with the service worker of the chrome extension and the one react app created.

How do I use Discord-RPC with Chrome Extension?

I want to make a chrome extension which parses youtube/soundcloud/... pages and gets current song's name. Then it should update user's rich presence status in discord. Like a did it in python there.
I have that one so far. Title already parsed, there's no problem. I have a problem with that code works. Because it doesn't work.
const clientId = '605777168739598338';
const scopes = ['rpc', 'rpc.api'];
const client = new RPC.Client({ transport: 'websocket' });
client.connect();
function updatePresence(title, time, icon) {
title = title.replace(/["]/g, "\\\"");
client.setActivity({
details: title,
startTimestamp: time,
largeImageKey: icon
}, 9999)
}
I also tried raw websocket connection but I'm stupid..
UPD:
The code above is in content.js.
browser.js is a file copied from root of module discord-rpc which i downloaded via npm.
manifest.json
{
"manifest_version": 2,
"name": "Tomori Player",
"version": "0.1.0",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["browser.js"]
},
"permissions": [
"ws://localhost:6463/*",
"tabs",
"webRequest",
"webRequestBlocking"
],
"content_scripts": [
{
"matches": [
"https://www.youtube.com/watch*",
"https://youtube.com/watch*"
],
"js": ["content.js"]
}
]
}
P.S. I'm so sorry. I'm new in JS.
There's a solution I found:
Chrome Extension parses page and sends sockets to another app
Another app on your PC gets these sockets and then sends RPC to Discord
Timeraa#7947 (PreMiD dev): Discord will disconnect almost immediately if you connect with a browser, trust me i tried. You will need to have an application running in the background
So, you can use PreMiD and push up PreMiD's presences list or make your own app to do it.

Chrome.identity not working in popup.js?

I'm trying to get the userInfo object from chrome.identity.getProfileUserInfo in my popup.js (which is a script used for popup.html) but I am getting the following error:
Uncaught TypeError: Cannot read property 'getProfileUserInfo' of undefined at onload
popup.js
onload = function(){
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
var url = tabs[0].url;
console.log(url);
});
chrome.identity.getProfileUserInfo(function(userInfo)
{
console.log(userInfo)
});
}
manifest.json
{
"manifest_version": 2,
"name": "QuickLink",
"description": "This extension allows you to quickly shorten and/or customize your url",
"version": "1.0",
"browser_action":
{
"default_icon": "icon.png",
"default_popup": "popup.html",
"default_title": "QuickLink"
},
"permissions":
[
"background",
"activeTab",
"clipboardWrite",
"tabs",
"notifications",
"identity",
"runtime"
]
}
I believe I have all the right permissions, and my tabs query works just fine, but for some reason, I don't have access to chrome.identity...any ideas why this might be or any work arounds so I can get the userInfo?
Would appreciate any help, thanks!
As answered in this thread you can only access it with a background script, not a content script.
It may require providing a "key" value in your manifest as well (if you're trying to get it working locally and it's not working). You can either use the same key as the one you get when you upload your extension to the webstore or try packing an extension to generate a new one (though I couldn't get this second approach working myself).

How to create a chrome (extension) webRequest listener?

I am trying to create a chrome (extension) webRequest listener. However, no matter what I try I cannot get access to the chrome.webRequest object - my program crashes with Uncaught TypeError: Cannot read property 'onCompleted' of undefined. Also debugging on the command line shows that chrome.webRequest does not exist.
My suspicion is that I am doing something wrong in the permissions, as I did not see many other stackoverflow questions or chrome bug reports with the same issues.
This is my manifest.json
{
"manifest_version": 2,
"name": "my extension",
"description": "my extension description",
"version": "1.0",
"permissions": [
"activeTab",
"webRequest",
"webRequestBlocking",
"https://<myextension>.com/*",
],
"page_action": {
"default_icon": { // optional
"19": "myextension.png", // optional
"38": "myextension.png" // optional
}
},
"content_scripts": [
{
"matches": ["https://<myextension>.com/*"],
"css": ["myextension.css"],
"js": ["jquery.js", "myextension.js"]
}
]
}
This is my myextension.js
var myfilter = {
urls: ['https://myextension.com/*']
}
function mycallback(){
console.log('received request response');
}
chrome.webRequest.onCompleted.addListener(mycallback, myfilter);
Any idea what I might be doing wrong?
I am running OSX 10.10.2 and chrome 40.0.2214.94.
Most of the Chrome API cannot be used in Content Scripts, including webRequest:
However, content scripts have some limitations. They cannot:
Use chrome.* APIs, with the exception of:
extension ( getURL , inIncognitoContext , lastError , onRequest , sendRequest )
i18n
runtime ( connect , getManifest , getURL , id , onConnect , onMessage , sendMessage )
storage
You need to process this event in a background page and communicate with the context script using Messaging.

Setting local storage in a Chrome extension

I'm using the following code to set local storage in a Chrome extension.
localStorage.setItem('userkey','123');
/* I've also tried this:
chrome.storage.sync.set({'userkey': 123}, function() {
// Notify that we saved.
message('Settings saved');
});
*/
manifest.json:
{
"manifest_version": 2,
"name": "Shopaholic",
"description": "All the latest sale items from your favourite clothes shops right on your home screen",
"version": "1.0",
"chrome_url_overrides": {
"newtab": "index.html"
},
"content_scripts": [
{
"matches": ["*://*/index.html"],
"css": ["css/style.css"],
"js": ["js/jquery.min.js"]
}
],
"options_page": "options.html",
"permissions": [
"storage"
]
}
However, I'm getting this error:
Uncaught SecurityError: Failed to read the 'localStorage' property
from 'Window': The document is sandboxed and lacks the
'allow-same-origin' flag.
If I use the commented out code above, I get:
Uncaught TypeError: Cannot read property 'sync' of undefined
Where have I gone wrong?
Read this - https://en.wikipedia.org/wiki/Same_origin_policy
Basically, its a web application security model concept.
So, to avoid this u need to disable the same origin policy on google chrome
So, if on desktop, open chrome from command line with this command
chrome.exe --disable-web-security
and then run your script, it shouldn't give this error then!

Categories