[英]Simple chrome extension
我正在構建一個簡單的chrome擴展名:manifest.json
{
"name": "Hello World",
"version": "1.0",
"manifest_version": 2,
"background": {
"scripts": ["js/background.js"]
},
"description": "My First Chrome Extension",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": ["tabs", "activeTab", "<all_urls>"],
"content_scripts": [
{
"matches": ["http://*/*"],
"js": ["js/script.js"]
}
]
}
background.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
scripts.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
console.log(sender.tab ?
"from a content script:" + sender.tab.url :
"from the extension");
if (request.greeting == "hello") {
sendResponse({farewell: "goodbye"});
document.write(request.greeting);
}
});
popup.html
<script src="js/script.js"></script>
新按鈕正確顯示在我的Chrome窗口中,但是當我單擊它時,會創建一個空對話框,盡管我希望它會說“你好”。 有什么建議嗎?
如果您在清單中設置"default_popup": "popup.html"
,則chrome打開一個窗口以顯示html頁面。 因此,從清單(不需要popup.html文件)中刪除此行,並在background.js中執行以下操作:
chrome.browserAction.onClicked.addListener(function() {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
console.log(response.farewell);
});
});
});
盡管我希望它說“你好”,但會創建一個空對話框
您正在從內容腳本而不是彈出代碼中調用document.write
因此它正在寫入實際的活動選項卡,而不是彈出窗口。
要在彈出窗口中顯示某些內容,您需要通過彈出窗口的代碼與其document
進行交互。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.