Chrome extension create new tab and send message from popup.js to content script of new tab

前端 未结 1 944
心在旅途
心在旅途 2020-12-21 06:12

I am developing a chrome extension where my popup.js receives a message from a content script on the current page and creates an array. Then on a button press, popup.js crea

相关标签:
1条回答
  • 2020-12-21 06:50

    As we discussed in the comments, I guess maybe $(document).ready is too late to receive messages from chrome.tabs.sendMessage, you can test it by comparing timestamps of console.log inside the callback and on the first line of the new tab's content scripts, as @wOxxOm mentioned.

    I just suggest moving message logic to background (event) page and starting the message passing from newtab-contentscript.js, in which you could control when to start sending the message.

    A sample code

    background.js

    let source = null;
    
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        // sent from another content script, intended for saving source
        if(request.action === 'putSource') {
            source = request.source;
            chrome.tabs.create({ url: 'newtab.html' });
        }
        // sent from newtab-contentscript, to get the source
        if(request.action === 'getSource') {
            sendResponse({ source: source });
        }
    });
    

    newtab-contentscript.js

    chrome.runtime.sendMessage({action: 'getSource'}, function(response) {
        $('#result').html(response.source);
    });
    
    0 讨论(0)
提交回复
热议问题