view background.js @ 3:89239e60d9e1 default tip

Enable on privileged pages There are contexts in Firefox (for example, the default new tab page) that contain links to http(s) resources but are considered privileged. In these contexts `menus.onShown` does not provide the link URL to the extension and Open Incognito disables the context menu entry. However, if the entry is not disabled, the `onClicked` listener will actually know the link URL because a user's click on the extension's menu item is considered to be an explicit permission, so Open Incognito could work. Keep the menu item enabled if the URL is not available. There is a drawback that the item will be enabled but do nothing if the actual link has an unknown/unsupported protocol, but this is probably a more rare situation.
author Denis Lisov <dennis.lissov@gmail.com>
date Sat, 09 Feb 2019 03:38:05 +0300
parents 3353f3c48b6b
children
line wrap: on
line source

/*
 * Copyright (C) 2018 Guido Berhoerster <guido+open-incognito@berhoerster.name>
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

'use strict';

function hasKnownProtocol(link) {
    return (link.startsWith('http:') ||
            link.startsWith('https:') ||
            link.startsWith('ftp:'));
}

function onMenuShown(info, tab) {
    let enabled = !tab.incognito &&
            (typeof info.linkUrl === 'undefined' || hasKnownProtocol(info.linkUrl));
    browser.menus.update('open-link-in-private-mode', {enabled});
    browser.menus.refresh();
}

async function onClicked(info, tab) {
    if(!hasKnownProtocol(info.linkUrl)) {
        return;
    }
    let activeTabs = await browser.tabs.query({
        active: true,
        currentWindow: false,
        windowType: 'normal'
    });
    console.log('active tabs:', activeTabs);
    let [windowId, ] = activeTabs.reduce((accumulator, currentTab) =>
            (currentTab.incognito && accumulator[1] < currentTab.lastAccessed) ?
            [currentTab.windowId, currentTab.lastAccessed] : accumulator,
            [-1, 0]);
    if (windowId < 0) {
        browser.windows.create({
            incognito: true,
            url: info.linkUrl
        });
    } else {
        browser.tabs.create({
            url: info.linkUrl,
            windowId
        });
    }
}

browser.menus.create({
        id: 'open-link-in-private-mode',
        title: browser.i18n.getMessage('openLinkInPrivateWindow'),
        enabled: false,
        contexts: ['link']
    },
    () => {
    if (browser.runtime.lastError) {
        console.error('Failed to create menu item:', browser.runtime.lastError);
        return;
    }
    browser.menus.onShown.addListener(onMenuShown);
    browser.menus.onClicked.addListener(onClicked);
});