【问题标题】:Cannot create a JS popup via the Chrome Extension popup无法通过 Chrome 扩展弹出窗口创建 JS 弹出窗口
【发布时间】:2015-05-11 09:02:21
【问题描述】:

我正在尝试创建我的第一个 Chrome 扩展程序,但我的 JS 无法正常工作。 我想要做的是,当我点击“Activer”时,它会显示一个弹出窗口,上面写着“你好”。

这是我在 github 中找到的一段代码,我试图适应我的代码。 当我检查我的扩展时,我收到如下错误:

Unchecked runtime.lastError while running tabs.executeScript: Cannot access contents of url "http://stackoverflow.com/questions/ask". Extension manifest must request permission to access this host.
at HTMLDivElement.hello (chrome-extension://clolnlfhhjonbfknjgebnmnfanpmcono/popup.js:4:15)

这是我的 manifest.json

{
"name": "e-kootsa",
"version": "1.0",
"manifest_version": 2,
"description": "Ce plugin vous permet d'écouter le texte d'une page",
"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
},
"options_page": "options.html"
}

这是我的 popup.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<style type="text/css">
body{
    margin: 0px;
    padding: 0px;
    font-family: Arial, Sans-serif;
    font-size: 20px;
    width: 200px;
}
.selection{
    text-align: center;
    margin-bottom: 5px;
}
.global{
    padding-top: 5px;
}

a{
    text-decoration: none;
    color: #000;
}
</style>
</head>
<body>
<div class="global">
    <div class="selection"><a href="options.html" target="_blank">Paramètres</a></div>
    <hr />
    <div class="selection" id="clickme"><a href="#">Activer</a></div>
    <hr />
    <div class="selection"><a href="about.html" target="_blank">À propos</a>        </div>
</div>
<script type="text/javascript" src="popup.js"></script>
</body>
</html>

这里是 popup.js

// var app = chrome.runtime.getBackgroundPage();

function hello() {
chrome.tabs.executeScript({
file: 'alert.js'
}); 
}

document.getElementById('clickme').addEventListener('click', hello);

这是我的 alert.js

alert('hello ' + document.location.href);
console.log('Tryhard');

我知道我一定犯了一些错误,但我仍然很难理解如何让事情发挥作用......

提前谢谢你!

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension popup


    【解决方案1】:

    Samurai's answer 有效,但未达到最优。

    如果您正在使用这样的活动标签,则不需要所有内容的全面许可。声明 &lt;all_urls&gt; 会在安装时向用户发出可怕的警告。

    有一个special permission, "activeTab",专门用于此目的。当用户调用扩展程序时(例如通过按下其按钮),它会授予当前选项卡的权限。

    "permissions": ["activeTab"],
    

    【讨论】:

      【解决方案2】:

      有关更保守的解决方案,请参阅Xan's answer

      ======

      它适用于活动选项卡,因此您需要在清单中为您希望它工作的每个可能的 URL 添加权限 = 所有 URL:"permissions": ["&lt;all_urls&gt;"]。因此,您的清单将如下所示:

      ...
      "browser_action": {
          "default_icon": "icon.png",
          "default_popup": "popup.html"
      },
      "permissions": ["<all_urls>"],
      "options_page": "options.html"
      

      只需添加它应该可以正常工作。

      【讨论】:

      • 查看我的答案以获得更保守的解决方案,以防您不知道这一点。
      • 谢谢,不知道有没有:)
      • 该死的我爱这个社区,它现在就像一个魅力!
      猜你喜欢
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-31
      相关资源
      最近更新 更多