// @ts-check

'use strict';

chrome.contextMenus.create({
    contexts: ['page', 'frame', 'selection', 'link', 'editable', 'image'],
    id: 'background_img',
    title: chrome.i18n.getMessage('title')
}, () => {
    console.log(chrome.runtime.lastError);
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
    chrome.tabs.sendMessage(tab.id, null, { frameId: info.frameId }, response => {

        if (chrome.runtime.lastError) {
            chrome.tabs.executeScript({ code: '', frameId: info.frameId }, () => {
                const reason = chrome.runtime.lastError ? 'security' : 'reload';
                alert(chrome.i18n.getMessage(reason));
            });
            return;
        }

        if (!Array.isArray(response) || response.length === 0) {
            const message = chrome.i18n.getMessage('failure');
            chrome.tabs.sendMessage(tab.id, message, { frameId: info.frameId }, result => {
                if (!result) return;
                chrome.tabs.create({
                    windowId: tab.windowId,
                    openerTabId: tab.id,
                    index: tab.index + 1,
                    url: 'https://github.com/foooomio/view-background-image/issues'
                });
            });
            return;
        }

        for (const image of response) {
            chrome.tabs.create({
                windowId: tab.windowId,
                openerTabId: tab.id,
                index: tab.index + 1,
                url: image
            });
        }

    });
});

@@ -1483,54 +1483,485 @@
     
-url: image%0A            %7D);%0A        %7D%0A%0A    %7D);%0A%7D);
+active: !shouldOpenInBackground(info),%0A                url: image%0A            %7D);%0A        %7D%0A%0A    %7D);%0A%7D);%0A%0A/**%0A * @param %7Bany%7D info%0A * @returns %7Bboolean%7D%0A * @description Currently this function works well only on Firefox.%0A */%0Afunction shouldOpenInBackground(info) %7B%0A    if (info.button === 1) return true;%0A%0A    if (info.modifiers && info.modifiers.length === 1) %7B%0A        const key = info.modifiers%5B0%5D;%0A        return key === 'Ctrl' %7C%7C key === 'Command';%0A    %7D%0A%0A    return false;%0A%7D
 %0A

Add a feature to open images in background tabs