2015-05-11 35 views
4

我試圖創建我的第一個Chrome擴展程序,但我遇到了問題以使我的JS正常工作。 我想要做的就是當我點擊「Activer」時,它會顯示一個彈出窗口,顯示「hello」。無法通過Chrome擴展程序彈出窗口創建JS彈出窗口

這是一個代碼,我發現在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

對於比較保守的解決方案看Xan's answer

======

它與激活的標籤,所以你需要在你的清單中添加的許可,您想要的工作一切可能的URL =所有網址:"permissions": ["<all_urls>"]。所以你的清單看起來是這樣的:

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

只要添加它應該可以正常工作。

+2

看到我的答案是更保守的解決方案,萬一你不知道這件事。 – Xan

+0

謝謝,不知道我是不是:) – Samurai

+0

該死的我喜歡這個社區,它現在就像一個魅力! – Jaeger

4

Samurai's answer有效,但達不到最佳效果。

如果您正在使用這樣的活動選項卡,則不需要全部權限。聲明<all_urls>將導致安裝用戶的可怕警告。

有一個special permission, "activeTab",專門爲此目的。當用戶調用擴展名時(例如按下按鈕),它授予當前選項卡的權限。

"permissions": ["activeTab"],