我正在做一个小的chrome扩展。现在我正在检查网站语言,并试图在popup.html
中显示该语言,但响应功能不起作用,我无法在弹出窗口中显示语言。有什么帮助吗?
popup.html
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Popup</h1>
<script src="./scripts/popup.js"></script>
</body>
</html>
popup.js
chrome.runtime.sendMessage({type: "getLanguage"}, function(selectedLanguage) {
// This function is not working
if(typeof selectedLanguage == "undefined") {
} else {
console.log(selectedLanguage)
}
})
content-script.js//内容脚本
const pageLanguage = document.querySelector("html").getAttribute('lang');
const language = languages.find(lang => lang.code === pageLanguage); // languages is an array which have all language codes
chrome.runtime.sendMessage({type: 'setLanguage', language: language.name});
background.js
// Background script
// Example of Chrome API use:
chrome.tabs.onCreated = () => {
console.log('New tab opened');
}
chrome.runtime.onMessage.addListener(
function (message, sender, sendResponse) {
switch (message.type) {
case 'setLanguage':
lang = message.language;
break;
case 'getLanguage':
console.log(lang);
sendResponse(lang);
break;
default:
console.error("Unrecognised message: ");
}
}
)
尝试长寿命连接端口,这更适合在contentscript和后台页面之间进行通信
https://developer.chrome.com/extensions/messaging#connect