0

I'm developing a Chrome extension that fetches data from the DOM. I have two contents scripts, one for the main frame (top-level frame) and another one for an iFrame.

I would like to be able to call a method that calls an iframe method and wait for the result.

I try to do it by using promises, post-message, and custom events.

//main-frame.js

window.addEventListener("message", this.frameMessages, false);

 const iframeElement = document.getElementById('iframeId');

function frameMessages(event){
   let dataReadyEvent = new CustomEvent('dataReady');
   iframeElement.dispatchEvent(dataReadyEvent);
}


let getDataAsync= async function getDataFromIFrame(): Promise<String> =>{
return new Promise(function (resolve) {
    chrome.runtime.sendMessage({service:'getData',frameId:frameId});
    iframeElement.addEventListener("dataReady", function dataReady() {
        resolve();
    });
}

//The promise is not been waited and there is no result :\
const data = await getDataAsync(); 
//iframe.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if(request.service === 'getData'){
     var element = document.getElementById(id);
      window.parent.postMessage({
                message: 'dataFromIFrame',
                frameGuid: frameGuid,
                data: element
            },
                "*"
            );
        }
    }
});

Lior Dadon
  • 233
  • 2
  • 10
  • `await` cannot be used at the top level of a normal script so you need to wrap the code inside an async IIFE e.g. `(async () => { ............ })()` – wOxxOm Sep 02 '21 at 15:57
  • See also the `workaround 2` in [this example](https://stackoverflow.com/a/68736674). – wOxxOm Sep 02 '21 at 16:12

0 Answers0