I am storing an array URLarry, using chrome.storage.sync.set in background.js and accessing it from options.js. Everything is running perfectly fine. I can use the URLarray in options.js with no problem.
But when I shutdown chrome and reopen it, all the data disappears. Please advice.
background.js
save["myKey"] = URLarray;
chrome.storage.sync.set(save, function() {
// console.log('Settings saved');
});
URLarray is populated as follows:
URLarray.push({website: websiteName, time:0, startTime:0, endTime:0});
options.js
chrome.storage.sync.get('myKey', function (obj) {
// console.log('myKey', obj);
x = obj.myKey;
console.log(x);
}
manifest.json
{
"name": "Animated Page Action",
"description": "This extension adds an animated browser action to the toolbar.",
"version": "1.2",
"background": {
"scripts": ["jquery-3.1.1.min.js","background.js"]
},
"page_action": {
"default_title": "First icon",
"default_icon": "icon_0.png"
},
"options_page": "options.html",
"permissions": ["tabs","storage"],
"manifest_version": 2
}
Your background code (which you don't include here) never actually reads data.
It does, however, write data, using that snippet you show, which is initialized by an empty array.
So each time you open the extension again, the data in background is empty, and it overwrites the saved data. To fix this, you must first perform initialization of your background URLarray from storage.
Related
I am developing my first browser extension for my website.
What this extension should basically do is to have a browser action which opens a pop-up where you can edit specific cookie values for the current page.
However, cookie A can exist on the page / while cookie B can exist on the page /checkout. So I don't want to list every cookie inside the pop-up, only the one which is active on the current page.
So, I searched the documentation and found that in order to communicate between web page and add-on you have to use the message system as described here
https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Communicating_with_the_web_page
To do so, my website has a JavaScript file which is loaded on every page. In this JavaScript I'm executing the following code
window.postMessage({type: 'FROM_PAGE', data: visibleCookies}, '*');
This piece of code is definitely executed, because I put a console.log before or after that statement, I can see that it's being logged.
Now, in my content script I want to listen to this by executing the following code
// experimentManager.js
console.log('testd');
window.addEventListener('message', (event) => {
console.log(event);
if (event.source !== window) {
return;
}
});
However, the console.log(event); is never executed. The listener is never activated. When I press the browser action so that the popup opens testd is logged into console, but still, the listener doesn't get any events. It's just not getting executed.
I don't know which files are relevant, but this is my manifest.json
// manifest.json
{
"manifest_version": 2,
"name": "My first addon",
"version": "1.0",
"description": "My first addon description",
"icons": {
"48": "icons/icon.png"
},
"browser_action": {
"default_icon": "icons/icon.png",
"default_title": "My first addon",
"default_popup": "popup/manage_experiment.html",
"browser_style": true
},
"permissions": [
"tabs",
"cookies",
"<all_urls>"
],
"content_scripts": [
{
"matches": ["*://*.mydomain/*"],
"js": ["experimentManager.js"]
}
]
}
And inside the pop-up script I'm executing this code among other things
browser.tabs.executeScript({file: "/content_scripts/experimentManager.js"})
.then(manageExperiments)
.catch(handleError);
which is probably the reason why the console.log('testd') gets executed, but nothing else?
What am I missing?
How can I store associated array in chrome local storage, and retrieve that in the same format? I want to save "identityKeyPair", which is in the form
identityKeyPair -> { pubKey: ArrayBuffer, privKey: ArrayBuffer }
I tried the below things. But not working out. I am getting [Object Object] on trying to retrieve it.
Saving to local storage
chrome.storage.sync.set({'identityKeyPair': JSON.stringify(identityKeyPair)}, function() {
alert('identityKeyPair saved');
});
Trying to retrieve
chrome.storage.sync.get(["identityKeyPair"], function(items){
if (items.identityKeyPair) {
alert(JSON.parse(items.identityKeyPair).pubKey);
}
Please follow these steps while you are using chrome.storage.sync
Declare storage permissions in your manifest.
manifest.json
{
"manifest_version": 2,
"name": "Storage",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"icons":{
"256":"img/icon.png"
},
"permissions": [
"storage"
],
"app": {
"launch": {
"local_path": "options.html"
}
},
"background": {
"scripts": ["js/app/background.js"]
}
}
Reload your App in chrome://extensions so that your manifest.json gets updated in your browser.
Follow the exact syntax of chrome.storage.sync with its callback function.
Sample.js
$(".thing").click(function() {
chrome.storage.sync.set({"myKey": "testPrefs"},function(){
alert("object stored");
})
chrome.storage.sync.get("myKey",function(obj){
alert(obj.myKey);
})
});
This will work for you. I tested this code in my chrome app.
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.
Further I need to save the filled data in local storage there I am not able to proceed ahead
Can you help me to get the code to execute local storage by set and get
enter image description here[entryt form2
Manifest
{
"background": {
"scripts": [ "background.js" ]
},
"browser_action": {
"default_icon": "t19.png"
},
"description": "Fill out web forms instantly with junk or custom data",
"icons": {
"128": "t128.png",
"48": "t48.png"
},
"manifest_version": 2,
"name": "Tatkal on budget style",
"options_page": "entry_form.html",
"permissions": [ "storage", "tabs", "http://*/*", "https://*/*" ],
"version": "1.0"
}`enter code here`
Background
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.create({'url': chrome.extension.getURL('entry_form.html')}, function(tab) {
// Tab opened.
});
});
Looking forward to have the code for local storage
Chrome extension doesnt support localstorage. You will have to use chrome.storage.sync (syncs data for the user across devices) or chrome.storage.local (local to the current chrome instance).
lets say u want to save a field called name with value as John.
Localstorage:
localstorage.setItem('name', 'Jogn');
Chrome extension
var obj = {
name:'Jogn'
}
chrome.storage.sync.set(obj, function () {
//success callback
});
to get the stored name use:
var keys = ['name'];
chrome.storage.sync.get(key, function (result) {
// the received result field will be an object
console.log(result.name);
});
I am a psychology student and I read papers very often. The university libraries provide the access to the databases but I need to use library search engine and log in every time. Quite annoying. I found a way to avoid jumping around the pages.
Here is the method:
I add "ezp.lib.unimelb.edu.au" to the end of the target database address after I found a paper in Google Scholar, then it will redirect to the library login page.
For example, the paper's address is:
http://www.sciencedirect.com/science/article/pii/S0006899315008550
I modified it as:
http://www.sciencedirect.com.ezp.lib.unimelb.edu.au/science/article/pii/S000689315008550
I want to create a Chrome Extension to finish this job on click (too lazy). I tried for hours but it does not work.
Here is what I have done:
I have three files in a folder:
First file: manifest.json
{
"manifest_version": 2,
"name": "Damn! Take me to the library!",
"description": "This extension automatically adds the 'ezp.lib.unimelb.edu.au' to the browser's address, allowing you to visit the databases bought by the library quickly",
"version": "1.0",
"browser_action": {
"default_icon": "unimelb.png",
"default_title": "Damn! Take me to the library!"
},
"background":{
"scripts":["popup.js"]
},
"permissions": [
"activeTab",
"tabs"
]
}
Second file: popup.js
function getCurrentTabUrlthenChangeIt(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
chrome.tabs.query(queryInfo, function(tabs) {
var tab = tabs[0];
var url = tab.url;
callback(url);
var newurl = url.replace('/',"ezp.lib.unimelb.edu.au/");
window.location.replace(newurl);
});
}
Third file: unimelb.png
When I load this folder into Chrome, it does not work.
It's the first time I use JS, anyone has any suggestions?
Thanks!
You can do this even without clicking. You can use the content script for this URL pattern so that your script gets injected to this page. Then you can send a message to the background script using chrome.runtime.sendMessage() and your listener will create a link you want here and then just reload the tab using chrome.tabs.update() with the new URL.
manifest.json
{
"name": "My extension",
...
"content_scripts": [{
"matches": ["http://www.sciencedirect.com/science/article/pii/*"],
"js": ["content-script.js"]
}],
...
}
content-script.js
chrome.runtime.sendMessage({loadURL: true});
background.js
chrome.runtime.onMessage.addListener(function(message, sender, response) {
if (message.loadURL) {
var newurl = sender.tab.url.replace("/", "ezp.lib.unimelb.edu.au/");
chrome.tabs.update(sender.tab.id, {url: newURL})
}
);
This is my first answer to the StackOverflow Community, I hope it helps.
Instead of making an extension, it would be a lot easier to make a bookmarklet which can be used in any browser...
Right click on the bookmark bar
Choose "Add page..."
Under "Name", enter whatever you want "Journal redirect" or whatever
Under "URL", copy and paste the following code (no spaces)
javascript:(function(){location.href=location.href.replace('sciencedirect.com/','sciencedirect.com/ezp.lib.unimelb.edu.au/');})();
Now when you're on the page, click that bookmark and it'll redirect you.
Update: Try this code in the URL for other domains
javascript:(function(){var%20l=location;l.href=l.origin+l.href.replace(l.origin,'ezp.lib.unimelb.edu.au/');})();
manifest.json
{
"manifest_version": 2,
"name": "Damn! Take me to the library!",
"description": "This extension automatically adds the 'ezp.lib.unimelb.edu.au' to the browser's address, allowing you to visit the databases bought by the library quickly",
"version": "1.0",
"browser_action": {
"default_icon": "unimelb.png",
"default_title": "Damn! Take me to the library!"
},
"background":{
"scripts":["background.js"]
},
"permissions": [
"activeTab",
"tabs"
]
}
background.js
//Wait for click
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(null, {
"file": "popup.js"
}, function(){
"popup.js";
console.log("Script Executed ...");
});
})
popup.js
// Change the url to library when on click
var l=location;l.href=l.origin+l.href.replace(l.origin, '.ezp.lib.unimelb.edu.au');
They work well.
It's so cool to finish the first chrome extension. Thank for the help from Mottie.
Anyone looking to edit the url based on some pattern can use the chrome extension Edit Url by Regex
For example for the scenario in this post, while using the extension, you can provide the regex as http.*/science/ and the value as http://www.sciencedirect.com.ezp.lib.unimelb.edu.au/science/
and click submit. The url will get updated as expected.
I'm trying to get a function to execute every time the user navigates to a new URL, but I can't get webNavigation to work for me. Here's what I'm trying so far:
manifest.json:
{
"manifest_version": 2,
"name": "My Extension name",
"description": "My Extension description",
"version": "1.0",
"background": {
"scripts": ["background.js"]
},
"permissions": ["webNavigation"]
}
background.js:
chrome.webNavigation.onBeforeNavigate = function () {
alert(123);
}
My breakpoint on the alert line never seems to hit. What am I doing wrong? Or is there another way to get an event every time the user navigates to a new page?
chrome.webNavigation.onBeforeNavigate is a chrome Event object.
To register a listener, you need to call addListener:
chrome.webNavigation.onBeforeNavigate.addListener(handler);
function handler(details) {
alert(123);
}
Futhermore, take a look at event filters.