Chrome Extension Local Storage: Background.html doesn't have access to localstorage? - google-chrome

Writing and reading from LocalStorage is working fine from my popup and tab. However, when I attempt to add a value from my background page, it doesn't seem to write at all. I'm viewing local storage in Chrome Developer Tools by refreshing and looking for the value to show.
In the following example code for background.html 'lastId' is displayed correctly in the alert when a new bookmark is added. However, the value is not stored. Additionally, the request for a known value appears to fail with no alert displaying. (Results are the same attempting both syntaxes shown below.)
<html>
<script>
// Grab the id of newly created bookmarks
chrome.bookmarks.onCreated.addListener(function(id) {
var lastId = id;
alert(lastId);
localStorage['lastId'] = lastId;
var testvalue = localStorage['309'];
alert(testvalue);
localStorage.setItem('lastId', lastId);
var testvalue2 = localStorage.getItem('309');
alert(testvalue2);
});
</script>
</html>
I keep thinking I must just be missing some small syntax issue or something but can't see anything. If my manifest declaration was incorrect I don't think the alert would work for the id. Stumped...
UPDATE: Turns out that you have to force reload of the extension on updates to background pages since they are persistent in browser memory when opened. That is why my saved code appeared not to work. It wasn't refreshed and I am duly embarrassed.

Hm, I can think about couple things.
You say that it works in a tab and a popup. This is very strange because it shouldn't (if by tab you mean content script). Content scripts are able to access only localStorage that belongs to a site they are injected. Popup, background, option pages, and any othe page from extension's folder can only access extension's own localStorage. Those two local storages and completely separated. So maybe you are inspecting wrong localStorage?
To see extension's own localStorage you need to inspect background or popup page and check resources tab in the inspector. To inspect site or content script localStorage you need to open regular inspector on the page.
Second moment is your localStorage assignment might be not what you are expecting.
If you run:
var lastId = 5;
localStorage['lastId'] = lastId;
you will get value 5 assigned to lastId property. So to read written value you need to run:
alert(localStorage['lastId']); //not localStorage['5']
If you want to store arrays then you would need to serialize/unserialize them through JSON as localStorage can store only strings.

Related

Script error for "Multiple URLs copy in Sources/Network tab" [duplicate]

Is it possible to extract multiple resources' URLs in Sources or Network tab of Chrome Dev Tools?
When I want to get URL of a single resource, I can do it with context menu function Copy link address
I can switch to this resource from Network to Sources tab and vice versa, but what if I have a need to get URLs of multiple resources at once? It is very cumbersome to copy them manually if resultset consists of 200-300 resources.
What I've tried so far:
To copy the whole folder from a sources tab, but from this answer I found out it is not possible for now.
To use $(selector) as specified in the Console reference, in a form of
$('img')
in case we need to fetch image URLs.
The complexity of this approach is that it's often hard to distinguish target images on a page that has hundreds of them, and furthermore, multiple versions of the same image (views, previews, small-sized icons and etc.) I.e. to match the element inside the tag with the needed resource is not that easy, as it seems. Also not all the file types have dedicated tags (as in the case with img).
Maybe I should use src tag with some modifiers? Any other suggestions?
make sure Network panel is active
switch devtools Dock side in the menu to a detached (floating) window
Next time you can press CtrlShiftD to toggle docking.
in the now detached devtools press CtrlShifti or ⌘⌥i on MacOS,
which will open devtools-on-devtools in a new window
Run the following code in this new window:
copy(UI.panels.network.networkLogView.dataGrid.rootNode().flatNodes.map(n => n.request().url()).join('\n'))
It'll copy the URLs of all requests that match current filter to clipboard.
Hint: save the code as a Snippet and run it in devtools-on-devtools window via the commands palette, CtrlP or ⌘P then type the snippet's name.
In old Chrome the code was different:
copy(UI.panels.network._networkLogView._dataGrid._rootNode._flatNodes.map(n => n._request._url).join('\n'))
copy(UI.panels.network.networkLogView.dataGrid.rootNode().flatNodes.map(n => n.request().urlInternal).join('\n'))
I found the above method too clunky, its way easier to use fiddler:
open fiddler (possibly install it)
filter on the domain name that you are interested in
clear the screen
refresh the web page
Select the fiddler output
right click and select copy just the URL's
Based on #wOxxOm, this worked for me:
var nodes = UI.panels.network._networkLogView._dataGrid._rootNode._flatNodes,
urls = [];
nodes.forEach(function() {
var req = arguments[0]._request;
if (req !== undefined) {
urls.push(req.url());
}
});
A selection and simple copy (Ctrl+C) work for me.
I select URLs in the Url column by the mouse.
Then I use the context menu to copy the list to the clipboard.
The clipboard contents then I can paste to Excel and get the URL list. It adds some empty lines though.

Multiple URLs copy in Sources/Network tab

Is it possible to extract multiple resources' URLs in Sources or Network tab of Chrome Dev Tools?
When I want to get URL of a single resource, I can do it with context menu function Copy link address
I can switch to this resource from Network to Sources tab and vice versa, but what if I have a need to get URLs of multiple resources at once? It is very cumbersome to copy them manually if resultset consists of 200-300 resources.
What I've tried so far:
To copy the whole folder from a sources tab, but from this answer I found out it is not possible for now.
To use $(selector) as specified in the Console reference, in a form of
$('img')
in case we need to fetch image URLs.
The complexity of this approach is that it's often hard to distinguish target images on a page that has hundreds of them, and furthermore, multiple versions of the same image (views, previews, small-sized icons and etc.) I.e. to match the element inside the tag with the needed resource is not that easy, as it seems. Also not all the file types have dedicated tags (as in the case with img).
Maybe I should use src tag with some modifiers? Any other suggestions?
make sure Network panel is active
switch devtools Dock side in the menu to a detached (floating) window
Next time you can press CtrlShiftD to toggle docking.
in the now detached devtools press CtrlShifti or ⌘⌥i on MacOS,
which will open devtools-on-devtools in a new window
Run the following code in this new window:
copy(UI.panels.network.networkLogView.dataGrid.rootNode().flatNodes.map(n => n.request().url()).join('\n'))
It'll copy the URLs of all requests that match current filter to clipboard.
Hint: save the code as a Snippet and run it in devtools-on-devtools window via the commands palette, CtrlP or ⌘P then type the snippet's name.
In old Chrome the code was different:
copy(UI.panels.network._networkLogView._dataGrid._rootNode._flatNodes.map(n => n._request._url).join('\n'))
copy(UI.panels.network.networkLogView.dataGrid.rootNode().flatNodes.map(n => n.request().urlInternal).join('\n'))
I found the above method too clunky, its way easier to use fiddler:
open fiddler (possibly install it)
filter on the domain name that you are interested in
clear the screen
refresh the web page
Select the fiddler output
right click and select copy just the URL's
Based on #wOxxOm, this worked for me:
var nodes = UI.panels.network._networkLogView._dataGrid._rootNode._flatNodes,
urls = [];
nodes.forEach(function() {
var req = arguments[0]._request;
if (req !== undefined) {
urls.push(req.url());
}
});
A selection and simple copy (Ctrl+C) work for me.
I select URLs in the Url column by the mouse.
Then I use the context menu to copy the list to the clipboard.
The clipboard contents then I can paste to Excel and get the URL list. It adds some empty lines though.

Chrome send data from background page to browser action

So I have a background page that listens in on tab changes
var tabHandler={
onTabUpdate:function(tabId, changeInfo, tab){
},
tabChanged:function(activeInfo) {
function tabChanged(tab){
var parser = document.createElement('a');//To extract the hostname, we create dom element
parser.href = tab.url;
var regex=/^(www\.)?([^\.]+)/
var matches=regex.exec(parser.hostname)//This gives us the hostname, we extract the website name
var website=matches[2];
var data=getDataForWebsite(website);//Data is a json array
//TRANSFER 'data' to Browser popup so that it can be displayed.
}
chrome.tabs.get(activeInfo.tabId,tabChanged);
},
init:function(){
chrome.tabs.onActivated.addListener(this.tabChanged);
}
}
tabHandler.init();
This piece of code gets the nam of the website and fetches a list of parameters based on the website. Now that I have the data, I am wondering how to show this data in the browser action popup. I want to pass this data to the browser Action adn then parse it there to replace existing content. How do I do that?
One thing you need to remember is that popup pages don't live while the popup is closed (unlike background pages). That means that you can't just transfer the data to the popup page since it doesn't exist anywhere at all time. Instead, whenever the popup is opened, the first thing you need to do is request the info from storage and display it however you want.
In your background page, when you receive the data for the current domain, you should save it somewhere: that could be in localStorage, or sessionStorage, or chrome.storage (check the documentation to see which one would make more sense in your use-case). You would want to save it indexed on the domain most likely, so that you can have the info saved from all the open tabs if needed.
Then whenever the popup is open, get the data for the current tab from the storage you used, and display the data in whichever way you want.
You can directly access background window from popup by chrome.extension.getBackgroundPage().
You can also directly access popup's window from background when it is open by chrome.extension.getViews({type:'popup'})[0].
Using these methods you can implement a messaging between popup and background.

Duplicate a tab in Chrome without Reloading the Page?

Is there any way to completely duplicate the state of a current tab in Google Chrome? I want an exact copy of the current state of the page without having to reload the page in another tab.
An example use case:
While browsing a "slideshow" on a news website, I want to preserve the current slide that I'm on, but create a duplicate so that I can continue viewing the next slide. If I simply Right-Click and "Duplicate" the tab, the new page will completely Reload, reprocessing all of the Javascript and running the pre-slideshow advertisement again.
In short "NO" you can't.
I am not expert on this
but a similar behavior can be achieved in some ways i know :
Dump the whole DOM
Never tried this though. You can convert the DOM to a string, pass it to the new window and then parse it as a document. This will let you lose your DOM events and State manipulation javascript. (But that's good for your case)
var dtab = window.open('about:blank', 'duplicate_a_tab');
dtab.document.open();
dtab.document.write("... yout html string ..");
dtab.document.close();
Develop an extension
Let the users continue on the current tab with the current state, your extension should be able to capture the screenshot of that area and open that screenshot in new tab. There are plenty of screenshot taking extensions are available in the market.
If that website is your own
You can develop your services that uses state locally like progressive web apps. Give a link separately to 'duplicate' which will eventually open the same URL in different tab with the same local state and with the flag do-not-sync.
This will not work when the user uses browser inbuilt duplicate
feature.

Are there "Pop Up Blockers"/Add Ons that change a post to a get in IE8?

We have some code where the user clicks a link which launches a pop up window. The code that creates the window then does an HTTP post to the window. Once the post has succeeded, the page is redirected (as a javascript location) to a PDF that was created during the post.
One person is getting an error where the posted data is not getting posted. In fact, the request is coming across as a GET.
Originally I thought this may be some kind of bookmark to the original page issue. But it happens in two different places that use the same concept in a different manner. And, since the post is triggered through JavaScript and the result is immediately relocated it would be no trivial matter to actually get a link to the original page.
So, the question is, are there any "pop-up" blocker like security tools that would allow pop-up's but convert all POSTS on them to GETS?
Example Call:
function LoadPDF(File){
document.forms[0].PDF.value = File;
win = "Window" + Math.round(Math.random()*100000);
open("",win,'toolbar=no');
function SubmitForm(){
document.forms[0].action = 'CreatePDF.cfm';
document.forms[0].target = win;
document.forms[0].submit();
}
//Give window time to open.
setTimeout(SubmitForm,550);
}
The code that creates the window then does an HTTP post to the window.
Popup blockers block popups as they are opening, which is pretty much the point of their existence. It would have to be a pretty lame popup blocker that allowed the popup to open and then translated the POST to a GET. It's possible a GreaseMonkey script or extension could translate it maybe.
Tell the user to disable any plugins/extensions and try again.