单击上下文菜单时打开扩展弹出窗口

问题描述 投票:1回答:4

我必须做一个扩展,当在上下文菜单中单击文本时,在回调中打开扩展菜单弹出窗口。

chrome.runtime.onInstalled.addListener(function() {
  var context = "selection";
  var title = "Google for Selected Text";
  var id = chrome.contextMenus.create({"title": title, "contexts":["selection"],
                                         "id": "context" + context});  
});

// add click event
chrome.contextMenus.onClicked.addListener(onClickHandler);

// The onClicked callback function.
function onClickHandler(info, tab) {
  var sText = info.selectionText;
  var url = "https://www.google.com/search?q=" + encodeURIComponent(sText);  


    //what i have put here to open extension popup


    };

在这种情况下,当我点击菜单时,我用这个搜索打开一个新标签。

google-chrome google-chrome-extension
4个回答
2
投票

不幸的是,它无法完成。

Chrome API不提供以编程方式打开扩展程序弹出窗口的方法。 Chromium团队拒绝了对此类选项的功能请求,并解释说:

浏览器和页面操作弹出窗口的理念是它们必须由用户操作触发。

这是source


4
投票

无法以编程方式打开默认浏览器操作弹出窗口。解决方法是使用内容脚本打开模式或灯箱并显示弹出窗口的内容。

另一种方法是 - 在上下文菜单项的clickhandler中,创建一个新选项卡并使其处于非活动状态,然后将该选项卡传递给chrome.windows.create api以创建一个新的弹出窗口。

    chrome.tabs.create({
      url: chrome.extension.getURL('popup.html'),
      active: false
  }, function(tab) {
      // After the tab has been created, open a window to inject the tab
      chrome.windows.create({
          tabId: tab.id,
          type: 'popup',
          focused: true
      });
  });

这只是一个解决方法。希望能帮助到你。


1
投票

您可以使用chrome.window API(documentation here)。

你想要的是这样的:

chrome.windows.create({
    url : "http://yourPopupUrl.com"
    focused : true
    type : "popup"});

这将在弹出模式下打开一个新窗口(没有顶部菜单栏)并加载“http://yourPopupUrl.com”。


0
投票

现在可以从处理程序内部以编程方式打开用户操作的浏览器操作弹出窗口。

browser.menus.create({
  id: "open-popup",
  title: "open popup",
  contexts: ["all"]
});

browser.menus.onClicked.addListener(() => {
  browser.browserAction.openPopup();
});

你可以阅读更多关于它here

编辑:

此功能仅适用于Firefox 57.在Chrome中,它仅在开发频道中可用。

资料来源:chrome/common/extensions/api/_api_features.json - chromium/src - Git at Google

© www.soinside.com 2019 - 2024. All rights reserved.