Last active
June 10, 2022 12:33
-
-
Save aphilas/7b7c0836608bbf5df49557c3074b71ed to your computer and use it in GitHub Desktop.
Create and send a custom event "GET_DATA." Wait for data from another event "RETURN_DATA" with a timeout. Useful for two-way communication between a content script and an injected script.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const delay = (duration=200) => new Promise((resolve) => { | |
setTimeout(() => resolve, duration) | |
}) | |
const getData = (timeout) => { | |
window.dispatchEvent(new CustomEvent("GET_DATA")) | |
let listener | |
const cleanup = () => { | |
if (listener) { | |
window.removeEventListener("RETURN_DATA", listener) | |
} | |
} | |
const data = new Promise((resolve) => { | |
listener = ((event) => { | |
resolve(event.detail?.data) | |
}) | |
window.addEventListener("RETURN_DATA", listener) | |
}) | |
return Promise.race([delay(timeout), draft]).finally(cleanup) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment