1

I have a problem with my chrome extension, the extension reads an object from the page and displays its contents in popup.js.

To read the object, popup executes injects.js which in turn injects script.js.

So what happens is, when inject.js completes execution the popup.js callback is called and renderData(mydata) is executed. I don't want this to happen until script.js is executed completely

Popup.js

chrome.tabs.executeScript(null, { file: "inject.js" }, function() {
  renderData(mydata);
});

inject.js

var s = document.createElement("script");
s.src = chrome.runtime.getURL("script.js");
(document.head || document.documentElement).appendChild(s);

script.js

 var data = {
    type: "FROM_PAGE",
    text: JSON.stringify(WIO.sessionInfo.context)
  };
  window.postMessage(data, "*");
Khawaja Asim
  • 1,327
  • 18
  • 38
Lorem Ipsum
  • 337
  • 2
  • 14

1 Answers1

1

The problem is that executeScript returns the last synchronously evaluated expression as the callback's parameter but a script with src runs asynchronously. BTW you forgot to specify the parameter.

Use textContent with literal code to run the script synchronously and send a DOM message, which is also synchronous, then leave the result in the last expression:

popup.js

chrome.tabs.executeScript(null, { file: "inject.js" }, ([mydata]) => {
  renderData(mydata);
});

inject.js

var data;
var eventId = 'event' + Math.random();
document.addEventListener(eventId, e => {
  data = JSON.parse(e.detail);
}, {once: true});

var script = document.createElement('script');
script.textContent = `(${eventId => {
  var data = JSON.stringify(WIO.sessionInfo.context);
  document.dispatchEvent(new CustomEvent(eventId, {detail: data}));
}})('${eventId}')`;
document.documentElement.appendChild(script);
script.remove();

data;

Alternatively you can use extension messaging to send the data to the popup (example).

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
  • Thank you @wOxxOm, the code run perfectly. However, i have a question. Why does the mydata object received in popup.js sorted in alphabetic order? – Lorem Ipsum Jan 07 '20 at 10:06
  • I don't know what you mean but I guess it's probably because of JSON.stringify+JSON.parse so try removing them both. Anyway, this is a separate issue so you should post another question if needed. – wOxxOm Jan 07 '20 at 10:16