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, "*");
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 ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.