Reputation: 626
I am trying to write a Chrome extension which can be disabled with a simple click on the browser action icon. I want to give the users this option because the extension raises a javascript alert when the alarm is triggered. The problem is that even after clearing the alarms, I am seeing alerts being raised. Also the icon click, which I want to work as a switch, isn't working as intended.
I have declared background.js as my background javascript file in manifest.json
"background": {
"scripts": ["alert.js"],
"persistent": true
},
"browser_action": {
"default_icon": "images/green.png",
"default_action": "popup.html",
"default_title": "Toggle Productiwitty"
}
background.js
var ExtensionOn = true;
function SwitchOn(e)
{
chrome.alarms.create("Alarm", {delayInMinutes: 0.1, periodInMinutes: 1} );
}
function SwitchOff(e)
{
chrome.alarms.clear("Alarm");
}
function showpopup()
{
alert("Inside function showpopup");
console.log("alert shown");
}
function click(e)
{
if(ExtensionOn)
{
SwitchOff();
console.log("switched off");
chrome.browserAction.setBadgeText({text: "Off"});
}
else if(!ExtensionOn)
{
SwitchOn();
console.log("switched on");
chrome.browserAction.setBadgeText({text: "ON"});
// Replace 15.0 with user selected time in minutes
}
//Toggle ExtensionOn
ExtensionOn = ~ ExtensionOn;
}
if(ExtensionOn)
{
chrome.alarms.onAlarm.addListener(showpopup);
}
chrome.browserAction.onClicked.addListener(click);
My "default_action": "popup.html" calls popup.js which creates the alarm
chrome.alarms.create("Alarm", {delayInMinutes: 0.1, periodInMinutes: 1} );
The idea is that once the extension is loaded, it should show a popup every 1 minute and if you click the icon, the extension gets disabled temporarily. On clicking the icon again, the same alert will be raised periodically.
Upvotes: 0
Views: 3277
Reputation: 4508
ExtensionOn = true
> true
ExtensionOn = ~ ExtensionOn
> -2
Boolean(ExtensionOn)
> true
If you want to toggle a boolean, use !
, not ~
.
if(ExtensionOn)
{
chrome.alarms.onAlarm.addListener(showpopup);
}
This is only called once, when a page first loads. If the extension isn’t on at that time, the listener won’t be added, and the function will never be called. I’d recommend moving the if
test into showpopup
.
Upvotes: 2
Reputation: 67
From https://developer.chrome.com/extensions/management#method-setEnabled
chrome.management.setEnabled(ExtId, true/false, callback)
But i'm not sure disabling the extension is what you actually want to do, once you disable it you have to go to chrome://extension and manually re-enable it.
Upvotes: 0