-
Notifications
You must be signed in to change notification settings - Fork 189
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3802 from asgerf/asgerf/use-message-from-extension
Add useMessageFromExtension hook
- Loading branch information
Showing
8 changed files
with
233 additions
and
309 deletions.
There are no files selected for viewing
27 changes: 27 additions & 0 deletions
27
extensions/ql-vscode/src/view/common/useMessageFromExtension.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { useEffect } from "react"; | ||
|
||
/** | ||
* Invokes the given callback when a message is received from the extension. | ||
*/ | ||
export function useMessageFromExtension<T>( | ||
onEvent: (event: T) => void, | ||
onEventDependencies: unknown[], | ||
): void { | ||
useEffect(() => { | ||
const listener = (evt: MessageEvent) => { | ||
if (evt.origin === window.origin) { | ||
onEvent(evt.data as T); | ||
} else { | ||
// sanitize origin | ||
const origin = evt.origin.replace(/\n|\r/g, ""); | ||
console.error(`Invalid event origin ${origin}`); | ||
} | ||
}; | ||
window.addEventListener("message", listener); | ||
|
||
return () => { | ||
window.removeEventListener("message", listener); | ||
}; | ||
// eslint-disable-next-line react-hooks/exhaustive-deps | ||
}, onEventDependencies); | ||
} |
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
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
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
Oops, something went wrong.