Skip to content

Instantly share code, notes, and snippets.

@shanomurphy
Last active August 15, 2020 02:45
Show Gist options
  • Save shanomurphy/d139f00c11bc199978d0be635eb09273 to your computer and use it in GitHub Desktop.
Save shanomurphy/d139f00c11bc199978d0be635eb09273 to your computer and use it in GitHub Desktop.
Chrome Extension Boilerplate – Toggle Using Browser Action
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);
if( extension_status == 'on' ) {
// do something
}
{
"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>"
]
}
@shanomurphy
Copy link
Author

shanomurphy commented Oct 7, 2016

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 and icon-off.png to complete.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
OSZAR »