Reputation: 939
I developed a chrome extension which uploads the data to my API.
It follows with signin
page and data-upload
page. As for this functionality, everything works fine.
The problem is when I click on the extension for the first time, it doesn't open. And on 2nd time clicking it opens. I need my extension to open immediately when user clicks the extension. I am not aware how to do that.
Here is my code:
manifest.json
{
"content_scripts": [
{
"matches": [ "http://*/*", "https://*/*"],
"js": [ "js/dataupload.js", "js/signin.js" ]
}
],
"name": "upload",
"version": "1.1",
"manifest_version": 2,
"description": "Quick access to upload data",
"content_security_policy": "script-src 'self' https://ajax.googleapis.com; object-src 'self'",
"permissions": [
"http://*/*",
"https://*/*",
"https://myapi.com/*",
"https://ajax.googleapis.com/*",
"management",
"tabs"
],
"icons": {
"128": "images/icon.png"
},
"background": {
"scripts": ["js/background.js"]
},
"browser_action": {
"default_title": "Upload APP",
"default_icon": "images/icon.png"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
background.js
chrome.browserAction.onClicked.addListener(function(tab) {
if (window.localStorage.getItem('user_api_key')) {
chrome.browserAction.setPopup({popup: "upload.html"});
}
else{
chrome.browserAction.setPopup({popup: "signin.html"});
}
});
Upvotes: 3
Views: 1227
Reputation: 77531
Code works as expected. First click is caught by chrome.browserAction.onClicked
that sets what happens on the next click.
There will be soon a direct solution in form of a chrome.browserAction.openPopup
function, but it's not in Stable yet.
So for now you have to reorganize the logic, as you can't open a popup if it doesn't happen immediately on click. You should set upload.html
as the default popup in the manifest, and then inside upload.html
check the condition and redirect if needed. Note that localStorage
is shared between background and popup.
So, manifest:
"browser_action": {
"default_title": "Upload APP",
"default_icon": "images/icon.png",
"default_popup": "upload.html"
},
upload.html
's code:
if (!window.localStorage.getItem('user_api_key')) {
window.location = chrome.runtime.getURL("signin.html");
}
Upvotes: 1