Last active
August 15, 2020 02:45
-
-
Save shanomurphy/d139f00c11bc199978d0be635eb09273 to your computer and use it in GitHub Desktop.
Chrome Extension Boilerplate – Toggle Using Browser Action
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var toggle = false; | |
var status = 'off'; | |
var the_tab_id = ''; | |
function set_status() { | |
toggle = !toggle; | |
status = 'off'; | |
if(toggle) { status = 'on'; } | |
} | |
function toggle_extension(tab){ | |
// Set icon | |
chrome.browserAction.setIcon({ path: 'icons/icon-'+status+'.png', tabId:tab.id }); | |
// Pass status variable & execute script | |
chrome.tabs.executeScript({ code: 'var extension_status = "'+status+'"' }); | |
chrome.tabs.executeScript({ file: 'inject.js' }); | |
// Set the tab id | |
the_tab_id = tab.id; | |
} | |
function my_listener(tabId, changeInfo, tab) { | |
// If updated tab matches this one | |
if (changeInfo.status == "complete" && tabId == the_tab_id && status == 'on') { | |
toggle_extension(tab); | |
} | |
} | |
chrome.browserAction.onClicked.addListener(function(tab) { | |
set_status(); | |
toggle_extension(tab); | |
}); | |
chrome.tabs.onUpdated.addListener(my_listener); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if( extension_status == 'on' ) { | |
// do something | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "My Extension", | |
"version": "0.0.1", | |
"manifest_version": 2, | |
"background": { | |
"scripts": ["background.js"], | |
"persistent": false | |
}, | |
"browser_action": { | |
"default_icon": "icons/icon-off.png" | |
}, | |
"permissions": [ | |
"activeTab", | |
"<all_urls>" | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A very simple boilerplate for creating a chrome extension that toggles on/off when the browser action icon is clicked and injects some script into the current tab. Add
icon-on.png
andicon-off.png
to complete.