0

I need to send two messages to my background script. The first one should get the title of the tab, the other one should send a message to store some data in local storage. This is what my code looks like right now:

// value should be filled in here by the first received message (the title)
let pageTitle;

// get the tab title from the background script
chrome.runtime.sendMessage({ type: 'GET_TAB_INFO' }, (title) => {
    pageTitle = title;
});

// include the retrieved tab title and store object in local storage
chrome.runtime.sendMessage({
    type: 'CLICK_EVENT,
    event: {
        eventName: 'ELEMENT_SELECTED',
        element: {
            EventId: uuidv4('some-random-uuid'),
            Metadata: {
                PageTitle
            }
        }
    }
});

My background script to get the title:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    const { type, ...rest } = request;
    if (type === 'GET_TAB_INFO') {
        chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
            sendResponse(tabs[0].title);
        });
    }
    
    return true;
}

The problem is that the pageTitle is always an empty string. How can I make the second sendMessage wait for the first one? I think I need to use async/await. I tried promises, but the syntax was very confusing.

erol_smsr
  • 1,454
  • 4
  • 24
  • 49
  • Since messaging is asynchronous your first callback runs after the second call was sent. Either move it inside the first callback or simply read the title via `document.title` instead of using messaging. – wOxxOm Apr 01 '21 at 11:46
  • @MathieuLescaudron I tried implementing it, but the Promise syntax was very confusing. I was hoping I could get some help doing async/await with this example. – erol_smsr Apr 01 '21 at 11:46

0 Answers0