How to fetch the value of a key from localstorage which is stored in your browser in a Chrome Extension - google-chrome-extension

I am new to developing Chrome Extensions.
I am trying to get the values for one of the keys which is stored in my browser's localstorage (inspect -> Application -> Localstorage). What I want to do is in my Chrome Extension, when you click a button, I just need it to fetch the value from localstorage for the page which is open in my browser's current tab.
This is the JS function which I am using -
chrome.storage.local.get(['granted.selected'], function(result) {
console.log('Value currently is ' + result.granted.selected);
});
granted.selected - is the name of the key whose value I want to fetch.
When this executes, I get "Value currently is undefined" whereas I want it to fetch the values stored in the above key (granted.selected).
What do I need to add to have this fetch the value for that key from my current open tab's localstorage?
In short - Just want to access a webpage's localStorage from a Chrome extension.
Any help will be greatly appreciated. Thanks!!

chrome.storage.local is not localStorage, it's a completely different storage API.
localStorage is a DOM storage.
To access DOM of a web page you need a content script [1].
Here's an example of programmatic injection in the popup script or in the background script:
chrome.tabs.executeScript({
code: 'localStorage["keyName"]'
}, ([result] = []) => {
if (!chrome.runtime.lastError) {
console.log(result);
// use the result here inside the callback
}
});
Notes:
You'll need permissions in manifest.json as explained in [1].
keyName is the name of the key as seen in devtools "Application" panel of the web page
each part of an extension has its own devtools console.

Related

How to get a variable which can be viewed from console

I'm coding an extension which downloads a file, before downloading the file, I need to get a token which is already generated from the website on loading.
This token can be viewed from the console by typing >GetPublicTokenResult
How can I read this variable into my content script?
I've tried the following:
chrome.storage.local.get(["GetPublicTokenResult"], function(items){ items = [ { "yourBody": "myBody" } ]
console.log(items);
});
but it seems that this variable is not stored in Storage, but it can be viewed in Memory snap
Content scripts run in an isolated environment from the page. They can only interact with the DOM, javascript code can't be accesed. You need to inject your code directly in the page. Check out Insert code into the page context using a content script for a detailed tutorial.

How to fix: Trying to capture a data in the options section of chrome extension for local.storage and use elsewhere?

I'm making a Google Chrome extension that has various parts. It has an iframe, a pop-up and an options page. Currently the iframe and pop-up communicate fine and send the collected data off to a database. However I want to capture some data from the options page (an email address) to be used elsewhere in the app. I planned to do this through capturing the email address and storing it but the code doesn't seem to be working.
I've attached the code I'm trying to use in options.js
function save_email(){
var email = document.getElementById('email').value;
chrome.storage.sync.set({
userEmail: email} );
};
I would hope to see it in local/session storage but nothing is there.

Can a browser extension access a locally-scoped variable in my script?

I noticed that browser extensions have the permission to access localStorage from any webpage (Get localStorage from within extension without loading a page) as well as cookies (Access cookies from Google Chrome extension). If you give them permissions to access all data on any webpage, then their glorified window objects can do this. (can browser extensions do more than that?)
Let's assume you have a script like this:
<script>
function SecretThing(){
// give the client a secret safe from browser extensions: (?)
var mySecret = Crypto.random()
// some cryptography with mySecret
}
var secretThing = new SecretThing();
</script>
Basically, I am wondering if I could do math on mySecret without ever revealing mySecret to a chrome extension. inside of a "SecretThing" object. I would only write getters to get stuff (e.g. signed or encrypted messages) from the secret.
I am not sure a window object could even access mySecret (or can it?), which is why I think that maybe a browser extension (which i said was mainly a window object) might also not be able to. What do you think? I have never made a browser extension before.

Save to chrome.storage on Setting Page and Read from Content script

I read in https://developer.chrome.com/extensions/storage
that it is possible for a content script to read directly from the storage api.
I have a setting page where i allow the user to save credentials, and i want to access those credentials from the content script. for some reason when i "get" from the content-script i get empty values...
Also -
How can i debug and see the Storage data from Chrome Developer tools?
chrome.storage.sync.get({'username':undefined,'password':undefined}, function(items) {
console.log(items.username)
username = items.username;
password = items.password;
console.log(typeof(username))
});
I Found that if i don't use the Dictionary in the .get api it works.
For some reason(probably a bug) when using the dictionary interface from content-script it doesn't find the data.
From the setting page the .get with dictionary worked.

Unable to use getBackgroundPage() api from a devtools extension

I am trying to write an extension that adds functionality to the Chrome devtools.
According to the devtools documentation, it says that the pages in devtools support very limited apis. Any API that is not supported can be access by accessing it through the background page, just as what contentscripts does.
Here is the relevant documentation snippet:
The tabId property provides the tab identifier that you can use with the chrome.tabs.* API calls. However, please note that chrome.tabs.* API is not exposed to the Developer Tools extension pages due to security considerations — you will need to pass the tab ID to the background page and invoke the chrome.tabs.* API functions from there.
Here is the source url: http://developer.chrome.com/extensions/devtools.inspectedWindow.html
However, when I try to do that, I get the following error in the console:
uncaught Error: "getBackgroundPage" can only be used in extension processes. See the content scripts documentation for more details.
Here is my code in my devtools.js script:
chrome.extension.getBackgroundPage().getLocation();
What am I doing wrong?
EDIT
I should describe my scenario first, and show how I am implementing it.
What I want to do is to display extra data in a devtools panel related to a webpage. In order to get that data, I will need to send a HTTP request in the same session as the page being debugged, because it requires authentication.
Use Case:
User browses to a particular URL. He is authenticated to the site. He then invokes devtools. The devtools panel opens up and a new panel shows up that has extra data related to the page.
Implementation:
1) DevTools script finds out the url of the page being inspected. If the url matches the site base hostname, then it opens a panel. In the callback of the panel creation, it sends a message to a background page, asking it to download a JSON payload from a debug endpoint on the same site, and then sends it to the devtools extension, wh ich then displays it.
Problems:
1) The background page gets the request, and downloads the URL. However the download is not using the same session as the user, so the download request fails.
2) From devtools window, I got the tabId of the inspected window. I send this tabId to the background page so that it can parse some stuff out of the url. However, chrome.tabs.get(tabId) does not return the tab.
To summarize, I need to
1) Get the background page to download data in the same session as the user's tab that is being debugged.
2) I need to have the background page be able to get access to the user's tab.
The APIs available to extension pages within the Developer Tools window include all devtools modules listed above and chrome.extension API. Other extension APIs are not available to the Developer Tools pages, but you may invoke them by sending a request to the background page of your extension, similarly to how it's done in the content scripts.
I guess the documentation is little ambiguous, By chrome.extension API they mean the Supported API's for content scripts.
So, you can use long lived communication for communication between inspected page and background page
Demonstration:
The following code illustrate scenario where a devtools page need some information from background page, it uses messages for communication.
manifest.json
Ensured permissions are all available in manifest file
{
"name":"Inspected Windows Demo",
"description":"This demonstrates Inspected window API",
"devtools_page":"devtools.html",
"manifest_version":2,
"version":"2",
"permissions":["experimental"],
"background":{
"scripts" : ["background.js"]
}
}
devtools.html
A trivial HTML File
<html>
<head>
<script src="devtools.js"></script>
</head>
<body>
</body>
</html>
devtools.js
Used Long lived Communication API's
var port = chrome.extension.connect({
name: "Sample Communication"
});
port.postMessage("Request Tab Data");
port.onMessage.addListener(function (msg) {
console.log("Tab Data recieved is " + msg);
});
background.js
Responded to communication request and passed trivial information using tab API()'s
chrome.extension.onConnect.addListener(function (port) {
port.onMessage.addListener(function (message) {
chrome.tabs.query({
"status": "complete",
"currentWindow": true,
"active": true
}, function (tabs) {
port.postMessage(tabs[0].id);
});
console.log("Message recived is "+message);
});
});
Sample Output received for trivial devtools.js here
Let me know if you need more information
EDIT 1)
For your question 1)
Can you make you call(s) from browser extension HTML Page\Content Script so same session is shared, i have tried both the ways in a sample and it is working form me, instead of code in background page- make the code in content script or browser action HTML Page.
Let me know if you are still facing problems.
For your question 2)
The following code always fetches current window user is browsing
manifest.json
Ensure you have tabs permission in your manifest.
{
"name":"Inspected Windows Demo",
"description":"This demonstrates Inspected window API",
"manifest_version":2,
"version":"2",
"permissions":["tabs"],
"background":{
"scripts" : ["background.js"]
}
}
background.js
chrome.tabs.query({
"status": "complete", // Window load is completed
"currentWindow": true, // It is in current window
"active": true //Window user is browsing
}, function (tabs) {
for (tab in tabs) { // It returns array so used a loop to iterate over items
console.log(tabs[tab].id); // Catch tab id
}
});
Let me know if you are still unable to get tab id of current window.

Resources