Programmatically set checkbox on optionsPage


(Github) #1

I know, i can open the Options Page with the following code from background.js. But how can i set a checkbox in the optionspage? The checkbox has the id=‘mycheck’.

browser.runtime.openOptionsPage().then(function() {
// try to mark checkbox, but how can i access the object 'mycheck'?			
},onError);

(Juraj Masiar) #2

You cannot access options page document from background script.
I would either:

  • use URL search params or #hashtags and then parse them in the options page javascript (that way the url would work by itself even when opened from another source). You would ofcourse need to change the way the Options page is opened (manually creating new tab with “/options_page.html” url).
  • in your callback function send message to that tab (you can get tab info as parameter in that callback function) using browser.tabs.sendMessage(tabInfo.id, {type: 'options_auto_check', id: 'chechbox_id'}). And then make sure you have registered message listener in your options page.

(Github) #3

I think, i have a solution. It seems to work.

in background.js, i use:

debug = true;
browser.runtime.openOptionsPage();

and in options.js:

var background_page = browser.extension.getBackgroundPage();    
window.addEventListener('load', function () {
    	if(background_page.debug) {
    		document.getElementById("mdebug").checked = true;
    	}
    }, false);

The default value of debug is false. If some condition is met, its set to true. Then i can load the options page. The options page now checks the background variable debug, if it is true. If thats the case, its does its job. I dont know, if i get it wrong, but it works for me. Thx for your help.


(jscher2000) #4

Wow, that is so much easier than passing messages. I notice it says on MDN that it doesn’t work in private windows, though, so I can’t use it for my extensions.


(Baptiste Thémine) #5

But normally the option page doesn’t open in private window. The correct behaviour in Chrome and Opera is when navigating in private browsing, openOptionsPage() opens a normal window.
In Firefox, there is an issue with that because it can open multiple option pages in private browsing. Maybe you should use browser.tabs.create() instead.


(Juraj Masiar) #6

I would seriously advice you to not use this approach. It feels very spaghetti-like programming and it brings complexity to your solution (especially with the mutation of a local variable).
You can avoid the mutation using the messaging. This will also keep the workflow straightforward:

  1. the background script opens Options page
  2. background script sends message to the Options page
  3. Options page reacts to the message