Chrome extension - saving login details for popup - javascript

I'm working on a Chrome extension that will require the user to log into an account in order to see their content. What I want to do is prevent the user from having to log in every time by saving some kind of cookie or localStorage with relevant login/ session data once they do login.
So far after doing a bit of research it seems that using Google Chromes local storage API would be the best way of doing this (would be great if someone could confirm this).
My issue is with setting and getting local storage. I've setup a dummy local storage scenario here just to try and get Chrome to store ANY kind of local storage for the extension:
Popup.js:
function setCookie(){
chrome.extension.sendMessage({name: 'setLoginCookie'}, function(otherResponse) {
console.log(otherResponse)
})
}
function getCookie(){
chrome.extension.sendMessage({name: 'getloginCookie'}, function(response) {
alert(response)
})
}
event.js:
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
if (request.name == 'setLoginCookie') {
var obj = {test:"test"}
chrome.storage.sync.set(obj, function() {
alert('Data saved');
});
}
if (request.name == 'getLoginCookie') {
chrome.storage.sync.get('test', function(data) {
sendResponse({ screenshotUrl: data.test });
})
}
return true;
});
When the setCookie function is executed I get the alert of 'data saved!' which would indicate to me it has worked but when I check the local storage on my extensions Chrome dev tools there is nothing there and if I call the getCookie function then it doesn't pick up anything.
Here are the permissions in my manifest.json:
"permissions": [
"storage",
"cookies",
"tabs",
"<all_urls>",
"pageCapture",
"downloads"
],
Have I used the wrong approach here? Is using chrome.storage.sync perhaps where i've gone wrong?
Thanks

chrome.storage.sync is not the same thing as local storage, you won't see the data saved using this method in the dev tools Local Storage.
You have a message mismatch. You're using {name: 'getloginCookie'} to send the message and the if statement is checking for getLoginCookie. The difference is the lower case l in the parameter you pass to the sendMessage function.

when I check the local storage on my extensions Chrome dev tools there is nothing there
Dev Tools do not expose chrome.storage inside them.
The "Local Storage" item exposes localStorage instead.
To inspect an extension's chrome.storage, you can use Storage Area Explorer extension or simply call chrome.storage.sync.get(null, (data) => { console.log(data) }) from the console.
Note: you don't have to delegate working with chrome.storage to your Event page. chrome.storage is directly accessible from all extension contexts - background, popup, options, content scripts. Don't layer on Messaging just for this.

Related

Firefox Extension Global Variables and onInstalled

I have a chrome extension that uses the Omnibox API. I want to port this extension to firefox by myself.
I've tried nearly everything that may help, and miserably, I'm exhausted and out of solutions.
Anyway, the extension basically does these steps in Chrome with no errors:
Load global variable called sites which is an array of object
var sites = [
{
"name":"ytb",
"desc":"YouTube",
"url":"https://www.youtube.com/results?search_query={%query%}"
},
{
"name":"ggl",
"desc":"Google",
"url":"https://www.google.com/search?q={%query%}"
},
{
"name":"dvand",
"desc": "Android Devs",
"url": "https://developer.android.com/s/results?q={%query%}"
},
{
"name":"bng",
"desc":"Bing",
"url":"https://www.bing.com/search?q={%query%}"
},
...
];
Save sites object to storage.local on runtime.onInstalled:
browser.runtime.onInstalled.addListener((details) => {
if (details.reason == "install") {
console.log("First install");
save(); //which saves sites to local storage...
load(); //which load sites from local storage...
}
});
Here is the save and load functions:
function save() {
browser.storage.local.set({"ssearch_sites":sites}, () => {
console.log("Saved!",sites);
sites = sites;
});
}
function load() {
browser.storage.local.get('ssearch_sites', (res) => {
console.log("Got!",res.ssearch_sites);
sites = res.ssearch_sites;
});
}
I think the problems could be relying on these:
onInstalled is not working
global variables such as sites are not stored (which is not quite possible).
local storage api is not working very well...
Oh, and I must say, when
I run the extension from these:
web-ext run
It works sometimes as expected, but when I download it from the store, it does not work. How could this even possible? I mean how works on testing and does not work on the production stage?
One more thing, do you know an alternative to local storage API?
Thanks!
Source codes are here:
Google Chrome version
Firefox version

How can I save data from background.js to local machine and fetch this data when required by a button on the popup.html page?

I just wanted to save my background.js data to my local machine and fetch the data to my extension whenever there happens to be a click on some popup.html button. Is there any way to do so and Is it different for different operating systems ?
All Chrome's extensions APIs are cross-platform. Regarding the storage, remember that content scripts run in the context of webpages, not extension pages. So when you access the localStorage from your contentscript, you are retrieving the storage from that particular page not the extension's storage.
Try this:
popup.js
document.getElementById("myButton").addEventListener("click", function(){
chrome.runtime.sendMessage({action: "getStorage", key: "name"}, function(response) {
alert(value.data);
});
});
background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === "getStorage") {
sendResponse({value: localStorage[request.key]});
}
});

How to use chrome.storage extension

My extension popup page gets data from a message from a sand-boxed page & scripts. I need to store this inside the chrome.storage, preferably using the storage.sync method. I'm getting this error:
Uncaught TypeError: Cannot read property 'sync' of undefined
I already added the permissions for storage inside my manifest.json.
... "permissions": ["storage"], ...
chrome.storage.sync undefined?
Google alsostates that no backgroud script is needed:
https://developer.chrome.com/extensions/storage
Quoting: Your extension's content scripts can directly access user data without the need for a background page.
What am I overlooking? Thanks in advance!
function receiveMessage(event) {
var data = event.data;
saveToStorage(data);
};
window.addEventListener("message", receiveMessage, false);
function saveToStorage(data)
{
if (!data) {
console.log('Error: No value specified. Nothing saved to storage.');
return;
}
chrome.storage.sync.set({'data': data}, function() {
console.log('Data saved to storage.');
});
};
Be sure to always reload your extension before testing something new. I never reloaded it before because it wasn't necessary, well until now :)
Also chrome.runtime.lastError comes in very handy!

Store informations locally? [duplicate]

I'm developing an extension for Google Chrome, and have run into some trouble.I created an options.html page and added it to the manifest.json file.The page shows properly.
I saved the options, and then went back to the page on which the extension is supposed to run.
Unfortunately, the Local storage for the options was returning a 'null' instead of the option. If I set the local storage option directly from the extension's JS script, it works fine but not if it was set from the options page.
Any idea how i can access the options.html local storage values from my Javascript file in the extension?
You can set them using either
localStorage["var"]=data;
or
localStorage.var=data;
Load them using
var myvar = localStorage.var;
You can read about the API here.
The correct method is:
if (typeof(localStorage) == ‘undefined’ ) {
alert(‘Your browser does not support HTML5 localStorage. Try upgrading.’);
}
else {
try {
localStorage.setItem(“name”, “Hello World!”); //saves to the database, “key”, “value”
}
catch (e) {
if (e == QUOTA_EXCEEDED_ERR) {
alert(‘Quota exceeded!’); //data wasn’t successfully saved due to quota exceed so throw an error
}
}
document.write(localStorage.getItem(“name”)); //Hello World!
localStorage.removeItem(“name”); //deletes the matching item from the database
}
REFERENCE: http://html5tutorial.net/tutorials/working-with-html5-localstorage.html

Chrome extension alternatives to local storage?

I'm looking for a storage mechanism which will persist across websites. I've got primitive data types numbers / strings which I need to store. localStorage doesn't work for me because it falls under the same origin policy. I need my data to be the same across all websites but much be tab specific and accessed via contentscripts.
Could someone suggest a suitable mechanism for achieveing this?
EDIT:
I'm currently implementing the first answers code and not having much look. I've got the following...
background.html
note: tabStorage is a class variable in this function
function store(){
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.req == "save") {
tabStorage[sender.tab.id] = request.data;
}
if(request.req == "load") {
sendResponse(tabStorage[sender.tab.id]);
}
});
}
contentscript.js
response is returning undefined
chrome.extension.sendRequest({req: "load"}, function(response) {
console.log("getting stak");
console.log(response.data);
});
what am I doing wrong? the code is accessing both load and save so I know it's getting there and back but undefined is returning. why?
You need to use extension's own localStorage which you access from a background page. If you need this information in a content script, you need to send a request to a background page using messaging, read it there, and send a result back to a content script in a response.
UPDATE
If you don't need the storage to keep values between browser restarts then you don't need the localStorage. Just store everything in a background page and identify tabs by their ids. Background page will keep the values as long as the browser is opened. For example:
content script:
//save
chrome.extension.sendRequest({cmd: "save", data: {param1: "value1", param2: "value2"});
...
//load
chrome.extension.sendRequest({cmd: "load"}, function(response) {
console.log("tab data:", response)
});
background page:
var tabStorage = [];
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if(request.cmd == "save") {
tabStorage[sender.tab.id] = request.data;
}
if(request.cmd == "load") {
sendResponse(tabStorage[sender.tab.id]);
}
});

Categories