无法通过Chrome扩展程序弹出窗口创建JS弹出窗口

时间:2015-05-11 09:02:21

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

我正在尝试创建我的第一个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');

我知道我一定犯过一些错误,但我仍然很难理解如何使事情发生......

提前谢谢!

2 个答案:

答案 0 :(得分:4)

Samurai's answer有效,但未达到最佳状态。

如果您正在使用此类活动标签,则不需要对所有内容进行一揽子许可。声明<all_urls>将导致用户在安装时发出可怕的警告。

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

"permissions": ["activeTab"],

答案 1 :(得分:2)

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

==

它适用于有效标签,因此您需要在清单中为您希望其工作的每个可能网址添加权限=所有网址:"permissions": ["<all_urls>"]。所以你的清单看起来像这样:

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

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

相关问题