Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

javascript - Sending data from background.js to popup.js not working using chrome.runtime.sendMessage

I am trying to send a string from background.js to popup.js. I actually get this string from contentscript.js where chrome.runtime.sendMessage and chrome.runtime.onMessage.addListener seem to be working for transferring data from contentscript.js to background.js. However, when I try doing the same thing for background.js to popup.js, chrome.runtime.onMessage.addListener() in popup.js file doesn't even seem to run.

popup.js


let typing = "";


chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        typing = request.typing; 
        document.getElementById("wpm").innerHTML = typing;
        
    }
);

background.js

let typing = "";
chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
        typing = request.greeting; 
    }
);

chrome.runtime.sendMessage({typing: typing});

contentscript.js

let sentence = "This is a test!";
let typing = "";

document.addEventListener('keydown', myInput);

function myInput(event){
    var input = event.which || event.keyCode;
    let typed = String.fromCharCode(input);

    typing = typing + typed;
    
    chrome.runtime.sendMessage({greeting: typing});

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...