Reputation: 233
I want to open my extension's options page when I click button in content.js.
I tried this, but does not opens options.html.
can someone help me please? thanks in advance
manifest.json
"options_page": "options.html",
options.html
<p>hello world</p>
content.js
let btt = document.querySelector('.settings-icon-hk');
btt.addEventListener('click', function(){
window.open('../options.html')
})
Upvotes: 3
Views: 2424
Reputation: 466
You can't open the options page directly from content.js
. Your browser will display an error message. Instead, you need to send a message to the background script and tell it to open the options page:
content.js:
let btt = document.querySelector(".settings-icon-hk");
btt.addEventListener("click", () => {
chrome.runtime.sendMessage("showOptions");
});
background.js:
chrome.runtime.onMessage.addListener((request) => {
if (request === "showOptions") {
[...]
}
});
Nevertheless, if you try to open the options.html
file using window.open('../options.html')
the browser will try to open the file on the server where it most probably doesn't exist. You have to tell the browser to open the options.html
file of the extension:
window.open(chrome.runtime.getURL('options.html'));
You have to tell the browser that it should open the option.html file of the extension:
window.open(chrome.runtime.getURL('options.html'));
Actually you don't need to take this detour and use a function provided by Chrome itself:
chrome.runtime.openOptionsPage();
This function has the advantage that it recognizes the "open_in_tab
" setting of manifest.json
.
background.js:
chrome.runtime.onMessage.addListener((request) => {
if (request === "showOptions") {
chrome.runtime.openOptionsPage();
}
});
You find this and more information about the option page at https://developer.chrome.com/extensions/options
Upvotes: 4