Google Chrome extenstion - local storage set and get - javascript

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);
});

Related

How can I save and retrieve associated array from chrome local storage

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.

chrome.storage.sync.set isn't saving data

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.

Default popup matching URL

I test an online-survey application. I have hundreds of textboxes in my application in which I have to enter some numbers for testing purposes. So I am creating a Chrome extension to fill the form. I did it and it works almost as I expected - except there is a small issue.
manifest.json:
{
"name": "FillForm",
"version": "1.0",
"manifest_version": 2,
"description": "FillForm",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["activeTab"]
}
Whenever I click on the browserAction button - it opens the popup.html where there is a textbox. If I enter 1 there, it will enter 1 for all the textboxes in my application - this is what I wanted.
Now I want to open the popup.html only for my application, i.e. matching URL http://example.com, because I do not want to enter any information in any other pages.
How can i achieve this?
I would inject the content of your popup.html in the pages matching specified URL.
This simplify your actions to fill your forms (you do no have to click on the extension icon)
It does not glut your browser with an additional icon
For doing this, first modify your manifest:
{
"name": "FillForm",
"version": "1.0",
"manifest_version": 2,
"description": "FillForm",
"content_scripts": [
{
"matches": ["http://*.xxx.com/*"], // put your URL pattern here
"js": ["popup_inject.js"]
}
],
"web_accessible_resources": ["popup.html"]
"permissions": ["activeTab"]
}
and in popup_inject.js
var iframe = document.createElement ("iframe");
iframe.src = chrome.extension.getURL ("popup.html");
iframe.style.position="absolute";
iframe.style.top="10px";
iframe.style.right="10px";
iframe.style.border="solid 1px #aaa";
document.querySelector("body").appendChild(iframe);
This is the exact purpose of Page Actions: to provide a button that's only visible on certain websites.
First, change your browser_action key to a page_action:
"page_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
You need to decide yourself when to show it. With declarativeContent API, you can provide a set of rules that say when you want to do it.
Add the declarativeContent permission:
"permissions": ["activeTab", "declarativeContent"]
Then, add a background script that will manage the rules. Since you don't need the background script to be always active, it's a good fit for an Event Page.
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
Now, the event page code:
// eventPage.js
// This only needs to run on install/update, rules are remembered
chrome.runtime.onInstalled.addListener(function(details) {
var rule1 = {
conditions: [
new chrome.declarativeContent.PageStateMatcher({
// See declarativeContent docs for more options
pageUrl: { hostEquals: 'www.example.com' }
})
],
actions: [ new chrome.declarativeContent.ShowPageAction() ]
};
// Remove existing rules, if any
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
// Then, add our rule1
chrome.declarativeContent.onPageChanged.addRules([rule1]);
});
});

Chrome extension inject js

I want to create a new chrome extension but it don't work.
I want to inject a js file into web page (all web page,not only one.If i push the chrome icon on google the script must execute,if i push the icon on facebook it must execute ect.)
this is background.js
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({
null,{file: "backgrounds.js"} });
});
this is backgrounds.js
document.body.innerHTML="display div elem with style and id";
this is manifest.json
{
"name": "MyExt",
"description": "an extension,what else?",
"version": "1.0",
"permissions": [
"activeTab"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["background.js"]
}
],
"browser_action": {
"default_title": "myExt"
},
"manifest_version": 2
}
what i wrong?
I'm on windows 8.1 Update 1 with chrome last version
Your manifest is wrong: you should set background.js as your background script:
"background" : { "scripts" : [ "background.js" ] },
and remove the "content_scripts" section.
The "activeTab" permission means that you don't need to specify host permissions to inject in the current tab upon browser action click, so no other permissions are needed.
The tabId argument is optional, you can just drop it instead of passing null. And your invocation is wrong (you're wrapping two arguments in a single object). Here's the correct way:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript({file: "backgrounds.js"});
});

Chrome Extension - edit a text field

I'm trying to write my first Chrome extension. It would, when clicked, automatically fill the fields of an ID and password for my University's login page (which has its form's auto-fill disabled).
It's a very specific page.
I have a few problem.
I've searched Google and SO but couldn't find an explanation on how to change the value of a text field through Chrome. I know how to do this in HTML and JavaScript, however I couldn't get the proper input to modify its text.
I've also tried using jQuery using a few examples I've found, but no luck.
I have an HTML page (popup.html) which calls a JavaScript file.
I've also tried placing the JS in a content script
Here's the manifest.json:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["jquery-1.7.2.min.js","content.js"]
}
]
}
One of my attempt of popup.js (which gets called from popup.html) is:
chrome.tabs.getSelected(null, function(tab) {
console.log(document)
});
I've also tried placing this code inside the content.js. same result,
It prints to console, however it prints the popup.html content..
I've also tried directly (and from the above method) to access an element directly by document.getElementById() but still no luck..
So,
Can anyone tell me what I'm doing wrong?
You need to inject a JavaScript file to the page using the "web_accessible_resources" attribute. See here:
manifest.json
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"permissions": [
"tabs", "http://*/*"
],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["jquery-1.7.2.min.js","content.js"],
"run_at": "document_start"
}
],
"web_accessible_resources": ["inject.js"]
}
inject.js
(function () {
console.log('test');
}());
content.js
(function (chrome) {
var js = document.createElement('script');
js.type = 'text/javascript';
js.src = chrome.extension.getURL('inject.js');
document.getElementsByTagName('head')[0].appendChild(js);
}(chrome));
Then just put the JavaScript code you want to use in inject.js to manipulate the page. Be sure to change matches to only match your University's login page.
The reason this is the case is because Chrome extensions can run and operate on their own regardless of which website you're on. And they can continue to process as you switch pages. They're in their own sandboxed environment.
I think you should use a simple content script that is executed on the login page. You don't even need any browser action or popup for that.
Here's a manifest:
{
"name": "Fill my password",
"version": "1.0",
"manifest_version": 2,
"description": "Fills my password on University login page",
"content_scripts": [
{
"matches": ["http://www.myuniversity.edu/login.html"],
"js": ["content.js"]
}
]
}
And here's a content script:
// define your username and password
var myUsername = '...';
var myPassword = '...';
// find the fiends in your login form
var loginField = document.getElementById('...');
var passwordField = document.getElementById('...');
// fill in your username and password
loginField.value = myUsername;
passwordField.value = myPassword;
// if you want, you can even automaticaly submit the login form
var loginForm = document.getElementById('...');
loginForm.submit();
Possible workaround(chrome extension): Autocomplete = on, but it could not work with some forms.

Categories

Resources