如何让Chrome扩展弹出窗口

qltillow  于 2022-12-06  发布在  Go
关注(0)|答案(2)|浏览(566)

我正在编写一个chrome扩展,它在弹出窗口中显示“https”网页的内容。到目前为止,我已经能够看到我放在manifest.json文件中的默认弹出窗口。我在清单中做的事情如下:

{
    "manifest_version": 3,
    "name": "My Rewards",
    "description": "Validate Identify",
    "version": "1.1",
    "permissions": [ 
        "identity",  "identity.email"
    ],
    "background": {
        "service_worker": "background.js"
      },
    "action": {
        "default_popup": "popup.html",
        "default_icon": {
            "16":"/images/icons/myRewards16.png",
            "32":"/images/icons/myRewards32.png",
            "48":"/images/icons/myRewards48.png",
            "128":"/images/icons/myRewards128.png"
        }        
    },
        "icons":{
            "16":"/images/icons/myRewards16.png",
            "32":"/images/icons/myRewards32.png",
            "48":"/images/icons/myRewards48.png",
            "128":"/images/icons/myRewards128.png"
}

我在看chrome扩展文档,上面说可以使用action.setPopup()方法来完成。我在这个问题上有点新手,我不知道正确的方法来添加方法,你能指导我吗?

qv7cva1a

qv7cva1a1#

只能使用chrome.action.setPopup()指定扩展包中的html。
如果网页允许iframe,则此示例有效。

manifest.json

{
  "name": "hogehoge",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  }
}

popup.html

<!DOCTYPE html>

<html>

<body style="min-width:800px;min-height:600px">
  <iframe id="iframe" width=800 height=600 src="https://nory-soft.web.app/"></iframe>
</body>

</html>

如果不允许,将导致错误。

如果网页不允许iframe,这个例子也可以用,但是点击链接会导致错误。布局经常会崩溃。

manifest.json

{
  "name": "hogehogehoge",
  "version": "1.0",
  "manifest_version": 3,
  "host_permissions": [
    "<all_urls>"
  ],
  "action": {
    "default_popup": "popup.html"
  }
}

popup.html

<!DOCTYPE html>

<html>

<body style="min-width:800px;min-height:600px">
  <iframe id="iframe" width=800 height=600></iframe>

  <script src="popup.js"></script>
</body>

</html>

popup.js

const elmIframe = document.getElementById("iframe");

const url = "https://developer.chrome.com/docs/extensions/";

fetch(url, {
  method: 'GET',
  mode: 'cors'
})
  .then(response => {
    if (response.ok) {
      return response.text();
    }
    throw new Error('Response was not ok.');
  })
  .then(data => {
    html = data;
    const blob = new Blob([data], { type: "text/html" });
    elmIframe.src = URL.createObjectURL(blob);
  })
  .catch(error => {
    console.log(error);
  })
xfb7svmp

xfb7svmp2#

本示例在新选项卡中显示扩展的文档。
popup.js

const url = "https://developer.chrome.com/docs/extensions/";

chrome.tabs.create({ url: url }, () => {
  window.close();
});

popup.html

<!DOCTYPE html>
<html>

  <body>
    <script src="popup.js"></script>
  </body>

</html>

manifest.json

{
  "name": "hoge",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "popup.html"
  }
}

相关问题