响应功能在popup.js Chrome扩展程序中不起作用 [英] Response function not working in popup.js chrome extension

查看:102
本文介绍了响应功能在popup.js Chrome扩展程序中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个小的chrome扩展程序.现在,我正在检查网站语言,并尝试在 popup.html 中显示该语言,但是响应功能不起作用,并且无法在弹出窗口中显示语言.有帮助吗?

I'm making a small chrome extension. Right now I'm checking for website language and trying to show that language in popup.html but response function is not working and I'm unable to show language in popup. Any help?

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//内容脚本

content-script.js // Content script

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.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: ");
        }
    }
)

推荐答案

尝试使用长期存在的连接端口,这对于在内容脚本和背景页面之间进行通信比较好

Try the long lived connections ports which is better for talking between the contentscript and the background page

https://developer.chrome.com/extensions/messaging#connect

这篇关于响应功能在popup.js Chrome扩展程序中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆