0

I am a new coder and would love some help with my chrome extension. I am trying to open a new tab that is in the background and web scrape data from it then closes it. However, I keep getting undefined instead of the actual data needed. The tab opens and closes with no problem but the alert to check returns undefined. Here is some sample code: content.js

chrome.runtime.onMessage.addListener(function(message, sender, response){
 if((message.from === 'popup') && (message.subject === 'getNewData')){
        var newObjson = {
            newPrice: document.getElementById("priceblock_ourprice").innerText,
            newAvailability: document.getElementById("availability").innerText
        };
            response(newObjson);
        };
    }
);

popup.js

var newProductPrice;
var newProductAvailability;

checkItem.onclick = function() {
        chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
            let tabIndex = tabs[0].index;
            chrome.tabs.create({ url: iURL, active : false, index:tabIndex+1 });
            chrome.tabs.onUpdated.addListener(function (updatedTabID , changeInfo, updatedTab) {
                if (changeInfo.status === 'complete' ) {
                    chrome.tabs.sendMessage(updatedTabID, 
                        {from: 'popup',
                            subject: 'getNewData'}, 
                        insertNewData);
                    alert(newProductPrice);
                    chrome.tabs.remove(updatedTabID);
                }
              });
        })
    }

    function insertNewData(data){
        newProductPrice = data.newPrice;
        newProductAvailability = data.newAvailability;
    }

The tab index line is just to open the new tab on the right of the current tab.

Chaleb
  • 1
  • 1
  • Move `alert` inside insertNewData. Or better yet, don't use alert, use proper debugging in devtools: the popup has its own devtools which you can open by right-clicking inside the popup. – wOxxOm Aug 30 '20 at 16:43
  • The insertNewdata alert pops after the alert from checkItem, so it's not updating the data before the tab is closed. – Chaleb Aug 31 '20 at 14:19
  • I'm not sure how to make them run in order using an async function and await. Any clarifications? – Chaleb Aug 31 '20 at 14:55
  • Of course you should move **all** code that runs after data is received inside the callback (insertNewData) including chrome.tabs.remove. – wOxxOm Aug 31 '20 at 15:28
  • thank you, sorry for all the trouble! Sorry for the duplicate posts, we were not sure what to do to advance. – Chaleb Aug 31 '20 at 15:58

0 Answers0