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

Categories

I'm trying to pass data from a popup to a content script, but I'm not having any luck. I got it to work the other way around (content -> popup) though. All I want to do is enter text into an input located in the popup and click a submit button which would insert that text into the dom of a web page.

This is what I have:

popup.html

chrome.extension.sendRequest({action:'start'}, function(response) {
    console.log('Start action sent');  
});

contentscript.js

function startExtension() { console.log('Starting Extension'); }

function stopExtension() { console.log('Stopping Extension'); }

function onRequest(request, sender, sendResponse) {
    if (request.action == 'start')
        startExtension()
    else if (request.action == 'stop')
        stopExtension()
    sendResponse({});
}

chrome.extension.onRequest.addListener(onRequest);
See Question&Answers more detail:os

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

1 Answer

You need to specify to which tab to send to. Like this:

chrome.tabs.sendMessage(tab.id, {action:'start'}, function(response) {
    console.log('Start action sent');
});

If you don't know which is the tab, you can either send to all (probably a bad idea) or make the tab send info first.

For more information check this page: Message Passing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...