Chrome 扩展程序中的弹出窗口

popup window in Chrome extension

本文关键字:窗口 扩展 程序 Chrome      更新时间:2023-09-26

我正在编写一个Chrome扩展程序,我希望当用户单击上下文菜单时弹出一个登录窗口,以便用户可以输入用户名和密码。在Chrome扩展程序中,我只发现chrome.pageAction.setPopupchrome.browserAction.setPopup可用于显示弹出窗口,但是它们仅在单击页面操作的图标或浏览器操作的图标时显示弹出窗口,而不是上下文菜单。当然,我可以使用javascript提示框来执行此操作,但问题是密码无法在提示框中屏蔽。所以我想知道是否有其他方法可以在Chrome扩展中创建弹出窗口。

谢谢!

选择:


  • showModalDialog(<String url> [, <object arguments>])打开一个类似对话框的窗口,您可以在其中加载 chrome 扩展程序中的页面。可以使用 HTML。

    不要使用showModalDialog,它将从Chrome中删除。

  • window.open(<String url> [, <String window_name>[, <String windowFeatures>]])打开一个窗口,与前面的方法不同,该窗口不显示为对话框。用户可以最小化窗口,并继续执行其他操作。

  • chrome.windows.create(<object createData [, <function callback>]>)(特定于 Chrome 扩展程序)创建一个新窗口,具有给定的参数(大小,url,位置等)。

所有这些方法都允许你(你的扩展)打开一个新窗口/对话框,并处理该页面中的逻辑。此页应与扩展打包在一起。
请参阅消息传递,将输入的数据传递到扩展。

演示

扩展中的选项卡可以使用 chrome.runtime.getBackgroundPage 直接访问背景页。我将在此演示中演示此功能,以及传统的消息传递方式:

manifest.json

{
  "name": "Dialog tester",
  "version": "1.0",
  "manifest_version": 2,
  "background": {
      "scripts": ["background.js"],
      "persistent": false
  },
  "content_scripts": [{
      "matches": ["<all_urls>"],
      "js": ["open-dialog.js"]
  }]
}

background.js

// Handle requests for passwords
chrome.runtime.onMessage.addListener(function(request) {
    if (request.type === 'request_password') {
        chrome.tabs.create({
            url: chrome.extension.getURL('dialog.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
                // incognito, top, left, ...
            });
        });
    }
});
function setPassword(password) {
    // Do something, eg..:
    console.log(password);
};

open-dialog.js

if (confirm('Open dialog for testing?'))
    chrome.runtime.sendMessage({type:'request_password'});

dialog.html

<!DOCTYPE html><html><head><title>Dialog test</title></head><body>
<form>
    <input id="pass" type="password">
    <input type="submit" value="OK">
</form>
<script src="dialog.js"></script>
</body></html>

dialog.js

document.forms[0].onsubmit = function(e) {
    e.preventDefault(); // Prevent submission
    var password = document.getElementById('pass').value;
    chrome.runtime.getBackgroundPage(function(bgWindow) {
        bgWindow.setPassword(password);
        window.close();     // Close dialog
    });
};

所用方法的文档

  • chrome.runtime.sendMessage(<request>, <function callback>)chrome.runtime.onMessage .addListener(<function listener>)
  • chrome.extension.getURL(<String path>)
  • chrome.runtime.getBackgroundPage(<function callback>)
  • chrome.tabs.create(<object createData> [, <function callback>])
  • chrome.windows.create(<object createProperties> [, <function callback>])