简体   繁体   中英

How to set focus to Firefox window using Web Extension

I am trying to create a Firefox addon that will bring the browser window to the forefront whenever a given event is fired.

This is my manifest:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "1.0",
  "description": "Test browser extension",

  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content.js"]
  }],

  "background": {
    "scripts": ["background.js"],
    "persistent": true
  },

  "permissions": [
    "notifications",
    "activeTab"
  ]
}

Content.js:

'use strict';

document.addEventListener('newOrderEvent', function() {
  console.log('New Order event received');
  browser.runtime.sendMessage('new-order-event');
});

Background.js:

'use strict';

var windowId;

function newOrderListener(message) {
  if (message === 'new-order-event') {
    console.log('Received event!');
    browser.windows.update(windowId, {
      drawAttention: true,
      focused: true,
      state: 'maximized'
    });
  }
}

browser.windows.getCurrent().then(function(window) {
  windowId = window.id;
});

browser.runtime.onMessage.addListener(newOrderListener);

The newOrderEvent is generated by my application's webpage and it is always being called at the right time, however sometimes the browser comes to the foreground and other times it doesn't and I don't understand exactly why. Furthermore the console output from the background.js is not being registered by the browser.

What I am doing wrong?

Note: I am using Firefox 52 and Windows 10.

If what you want is a TAB to make itself focused, then you are mistaken with what windowId is. WindowId will be the ID of the window, not of a tab, and the way you are setting it, it will only ever be a single value, the first windowID when the extension is loaded

if you change background.js to the following

function newOrderListener(message, sender) {
    if (message === 'new-order-event') {
        console.log('Received event for window %s, tab %s', sender.tab.windowId, sender.tab.id);
        browser.windows.update(sender.tab.windowId, {
            drawAttention: true, 
            focused: true, 
            state: 'maximized'}
        ).then(() => browser.tabs.update(sender.tab.id, {
            active: true
        }));
    }
}
browser.runtime.onMessage.addListener(newOrderListener);

Then any tab that has the content script loaded (which is basically every tab in your code) will be able to focus itself by

document.dispatchEvent(new Event("newOrderEvent"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM