[英]chrome.runtime.sendMessage not working in Chrome Extension
[英]sendMessage not working in chrome extension
我試圖做一個簡單的chrome擴展。 如果有人可以提供幫助,我會很高興。
目標:當您單擊擴展彈出窗口(popup.html)中的按鈕時,當前網頁的標題將顯示在div中(ID為“div1”)。
問題:我已經搜索了互聯網這樣做,發現傳遞消息可以用來實現同樣的目的。 所以我嘗試了一下。 但它不起作用。 我想知道出了什么問題。
狀態:
=擴展已成功導入chrome。
=單擊擴展圖標時,它會顯示正確的彈出窗口。
=單擊按鈕時沒有任何反應。
=開發者控制台顯示沒有錯誤。
文件:
//manifest.json
{
"manifest_version": 2,
"name": "some_name_extension",
"version": "0.0.1",
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["jquery-3.2.1.js", "content_script.js"]
}
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
}
}
=====================================
<!-- popup.html -->
<! doctype html>
<html>
<head>
<title>
</title>
<script type="text/javascript" src="popup.js">
</script>
<style>
html
{
height: 200;
width: 200;
}
</style>
</head>
<body>
<button id="btn1">
click me!
</button>
<div id="div1">
(title will be displayed here)
</div>
</body>
</html>
=====================================
//content_script.js
document.addEventListener('DOMContentLoaded', function() {
var title1=document.getElementsByTagName("title")[0].innerHTML;
chrome.extension.onMessage.addListener(
function(msg, sender, sendResponse) {
if(sender=="popup")
{
chrome.extension.sendMessage(title1,"content","1");
}
});
});
=====================================
//popup.js
document.addEventListener('DOMContentLoaded', function() {
var mainBtn = document.getElementById('btn1');
mainBtn.addEventListener('click', function() {
chrome.extension.sendMessage("button_clicked","popup","1");
});
chrome.extension.onMessage.addListener(
function(msg, sender, sendResponse) {
if(sender=="content")
{
document.getElementById("div1").innerHTML=msg;
}
}
);
});
鏈接到jquery腳本文件: https : //code.jquery.com/jquery-3.2.1.js
sender
是一個由瀏覽器自動設置的對象,而不是您可以自己傳遞的字符串。 使用devtools調試器通過在回調中設置斷點來檢查代碼和變量,不要盲目地編寫代碼。 sender
,因為內容腳本無論如何都無法互相發送消息。 從彈出窗口向內容腳本發送消息的正確方法是chrome。 使用tabId
作為第一個參數的選項卡 .sendMessage :
chrome.tabs.query({active: true, currentWindow: true}, ([tab]) => { chrome.tabs.sendMessage(tab.id, { action: 'setTitle', title: title1, }); });
要一次發送多個值,請使用對象: {action: 'setTitle', title: title1}
或{action: 'buttonClicked', data: 1}
等等。
chrome.extension
進行消息傳遞,請使用chrome.runtime
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.