Here’s how to make it so clicking the Page Action icon of a Chrome extension opens the extension options page. This code will open a new options page if one is not open, or switch to it if it’s already option.
You will need the “tabs” permission in your manifest.json:
"permissions": [
"tabs",
],
"background": {
"scripts": ["background.js"],
"persistent": false
}
Put this code in your background.js file:
function openOrFocusOptionsPage() {
var optionsUrl = chrome.extension.getURL('options.html');
chrome.tabs.query({}, function(extensionTabs) {
var found = false;
for (var i=0; i < extensionTabs.length; i++) {
if (optionsUrl == extensionTabs[i].url) {
found = true;
console.log("tab id: " + extensionTabs[i].id);
chrome.tabs.update(extensionTabs[i].id, {"selected": true});
}
}
if (found == false) {
chrome.tabs.create({url: "options.html"});
}
});
}
chrome.extension.onConnect.addListener(function(port) {
var tab = port.sender.tab;
// This will get called by the content script we execute in
// the tab as a result of the user pressing the browser action.
port.onMessage.addListener(function(info) {
var max_length = 1024;
if (info.selection.length > max_length)
info.selection = info.selection.substring(0, max_length);
openOrFocusOptionsPage();
});
});
// Called when the user clicks on the browser action icon.
chrome.browserAction.onClicked.addListener(function(tab) {
openOrFocusOptionsPage();
});
Hi Adam,
Thanks for the help! I’m looking at the ‘info.selection.length’ bit and trying to figure out what that is exactly (I’ve already read through the Chrome extension documentation but couldn’t find anything). Could you tell me what that 1024 number exactly is? Thank you!
Hi Sun,
I actually don’t remember exactly how this code works anymore. I’m limiting the selection length to 1024, an arbitrary size, but I’m not sure why I decided to do that. It just worked for me, I think.