chrome extension contextMenu contextType includes browser_action didn't mathch documentUrlPatterns

63 views Asked by At

I create a contextMenu with contexts is ['all'] and documentUrlPatterns is [':///*.pdf'].It works well in pages.But it always appear in browser_action even throught the page url's suffix isn't '.pdf'. I want this contextMenu don't appear in browser_action when page url don't endsWith '.pdf'. How to resolve this problem?

contextMenu create code:

chrome.contextMenus.create({
  id: 'PDF_TOP',
  title: 'PDF编辑/打印/转换',
  contexts: ['all'],
  documentUrlPatterns: ['*://*/*.pdf']
})

contextMenu in page behavior: enter image description here enter image description here

contextMenu in browser_action beahvior: enter image description here enter image description here

1

There are 1 answers

1
Yu Zhou On

You can listen to chrome.tabs.onActivated and add or remove the context menu based on if the current page is PDF. It won't show in browser_action.

You can refer to the code below:

chrome.tabs.onActivated.addListener(function (info) {
    var tab = chrome.tabs.get(info.tabId, function (tab) {
        if (tab.url.indexOf(".pdf") > 0) {
            chrome.contextMenus.create({
                "id": "PDF_TOP",
                title: "PDF test/print",
                contexts: ["all"]
            });
        } else {
            chrome.contextMenus.remove("PDF_TOP", null);
        }
    });
});