Skip to content

Instantly share code, notes, and snippets.

@aphilas
Last active June 10, 2022 12:33
Show Gist options
  • Save aphilas/7b7c0836608bbf5df49557c3074b71ed to your computer and use it in GitHub Desktop.
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.
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