Response function not working in popup.js chrome extension

跟風遠走 提交于 2021-01-07 02:41:11

问题


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

<!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

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

回答1:


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



来源:https://stackoverflow.com/questions/65071740/response-function-not-working-in-popup-js-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!