Setting local storage in a Chrome extension - javascript

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!

Related

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

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.

Why is .click() not working in Chrome Extension?

Alright so I'm starting to learn how to build chrome extensions so i can automate some tasks at work.
I Set up my manifest.json file as follows:
{
"manifest_version": 2,
"name": "Test",
"version": "1.0",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["content.js"]
}
]
}
my content.js file seems to be working fine, when I console.log() stuff it shows up in the website's console. However, when I try to use the .click(); method with query selector, it shows an error.
var this_button = document.querySelector(".nav-link"); this_button[0].click();
The error shown when I try to load the Extension is:
Uncaught TypeError: Cannot read property '0' of null
the websites console reads this error:
Uncaught TypeError: Cannot read property 'click' of undefined
Any ideas? I am not using Jquery and cannot use it for this project, as I cannot download anything external onto work computer. This needs to be done with Vanilla JS.
this_button[0].click() is incorrect - you should be using this_button.click()

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.

Cannot call chrome.alarms.create() from a content script

I'm developing a Chrome extension right now.
My problem is that when I call chrome.alarms.create(), I get the following error:
Uncaught TypeError: Cannot read property 'create' of undefined
I have these files in my extension package:
manifest.json
{
"manifest_version": 2,
"name": "Tool",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"permissions": ["background", "tabs", "webNavigation", "alarms"]
}
myscript.js
chrome.alarms.create("aaa", {"when":Date.now()+5000});
chrome.alarms.onAlarm.addListener(function(alarm){
console.log("hello");
});
background.js
chrome.pageAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {file: "myscript.js"});
});
When I call chrome.alarms.create() in background.js, it works fine.
But, when I call the function in myscript.js, it causes the error.
What is the cause and how can I fix this problem?
You can't access most Chrome APIs from a content script. You will need to use the Messaging API to send a message to the background page which can then call the Alarms API.
https://developer.chrome.com/extensions/messaging
https://developer.chrome.com/extensions/content_scripts

Categories