-
Notifications
You must be signed in to change notification settings - Fork 19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: Add visibility handling to allow proactive event flushing. #607
Merged
Merged
Changes from 6 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
564f5b8
WIP
kinyoklion 270bca4
Refactoring
kinyoklion da3ea00
Fix goals test, remove state detector tests.
kinyoklion 18467ca
Merge branch 'main' into rlamb/SDK-564/visibility-state-handling
kinyoklion cabf104
Lint
kinyoklion 5d529f1
Merge branch 'rlamb/SDK-564/visibility-state-handling' of github.com:…
kinyoklion 1ab7c0f
Account for keepalive in common tests.
kinyoklion 77564da
Make cleanup smaller.
kinyoklion File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
/** | ||
* All access to browser specific APIs should be limited to this file. | ||
* Care should be taken to ensure that any given method will work in the service worker API. So if | ||
* something isn't available in the service worker API attempt to provide reasonable defaults. | ||
*/ | ||
|
||
export function isDocument() { | ||
return typeof document !== undefined; | ||
} | ||
|
||
export function isWindow() { | ||
return typeof window !== undefined; | ||
} | ||
|
||
/** | ||
* Register an event handler on the document. If there is no document, such as when running in | ||
* a service worker, then no operation is performed. | ||
* | ||
* @param type The event type to register a handler for. | ||
* @param listener The handler to register. | ||
* @param options Event registration options. | ||
* @returns a function which unregisters the handler. | ||
*/ | ||
export function addDocumentEventListener( | ||
type: string, | ||
listener: (this: Document, ev: Event) => any, | ||
options?: boolean | AddEventListenerOptions, | ||
): () => void { | ||
if (isDocument()) { | ||
document.addEventListener(type, listener, options); | ||
return () => { | ||
document.removeEventListener(type, listener, options); | ||
}; | ||
} | ||
// No document, so no need to unregister anything. | ||
return () => {}; | ||
} | ||
|
||
/** | ||
* Register an event handler on the window. If there is no window, such as when running in | ||
* a service worker, then no operation is performed. | ||
* | ||
* @param type The event type to register a handler for. | ||
* @param listener The handler to register. | ||
* @param options Event registration options. | ||
* @returns a function which unregisters the handler. | ||
*/ | ||
export function addWindowEventListener( | ||
type: string, | ||
listener: (this: Document, ev: Event) => any, | ||
options?: boolean | AddEventListenerOptions, | ||
): () => void { | ||
if (isDocument()) { | ||
window.addEventListener(type, listener, options); | ||
return () => { | ||
window.removeEventListener(type, listener, options); | ||
}; | ||
} | ||
// No document, so no need to unregister anything. | ||
return () => {}; | ||
} | ||
|
||
/** | ||
* For non-window code this will always be an empty string. | ||
*/ | ||
export function getHref(): string { | ||
if (isWindow()) { | ||
return window.location.href; | ||
} | ||
return ''; | ||
} | ||
|
||
/** | ||
* For non-window code this will always be an empty string. | ||
*/ | ||
export function getLocationSearch(): string { | ||
if (isWindow()) { | ||
return window.location.search; | ||
} | ||
return ''; | ||
} | ||
|
||
/** | ||
* For non-window code this will always be an empty string. | ||
*/ | ||
export function getLocationHash(): string { | ||
if (isWindow()) { | ||
return window.location.hash; | ||
} | ||
return ''; | ||
} | ||
|
||
export function getCrypto(): Crypto { | ||
if (typeof crypto !== undefined) { | ||
return crypto; | ||
} | ||
// This would indicate running in an environment that doesn't have window.crypto or self.crypto. | ||
throw Error('Access to a web crypto API is required'); | ||
} | ||
|
||
/** | ||
* Get the visibility state. For non-documents this will always be 'invisible'. | ||
* | ||
* @returns The document visibility. | ||
*/ | ||
export function getVisibility(): string { | ||
if (isDocument()) { | ||
return document.visibilityState; | ||
} | ||
return 'visibile'; | ||
} | ||
|
||
export function querySelectorAll(selector: string): NodeListOf<Element> | undefined { | ||
if (isDocument()) { | ||
return document.querySelectorAll(selector); | ||
} | ||
return undefined; | ||
} |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import { addDocumentEventListener, addWindowEventListener, getVisibility } from './BrowserApi'; | ||
|
||
export function registerStateDetection(requestFlush: () => void): () => void { | ||
// When the visibility of the page changes to hidden we want to flush any pending events. | ||
// | ||
// This is handled with visibility, instead of beforeunload/unload | ||
// because those events are not compatible with the bfcache and are unlikely | ||
// to be called in many situations. For more information see: https://developer.chrome.com/blog/page-lifecycle-api/ | ||
// | ||
// Redundancy is included by using both the visibilitychange handler as well as | ||
// pagehide, because different browsers, and versions have different bugs with each. | ||
// This also may provide more opportunity for the events to get flushed. | ||
// | ||
const handleVisibilityChange = () => { | ||
if (getVisibility() === 'hidden') { | ||
requestFlush(); | ||
} | ||
}; | ||
|
||
const removeDocListener = addDocumentEventListener('visibilitychange', handleVisibilityChange); | ||
const removeWindowListener = addWindowEventListener('pagehide', requestFlush); | ||
|
||
return () => { | ||
removeDocListener(); | ||
removeWindowListener(); | ||
}; | ||
} |
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
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 |
---|---|---|
|
@@ -6,6 +6,8 @@ import { | |
TypeValidators, | ||
} from '@launchdarkly/js-client-sdk-common'; | ||
|
||
const DEFAULT_FLUSH_INTERVAL_SECONDS = 2; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Realized this wasn't in as I was testing things out. |
||
|
||
/** | ||
* Initialization options for the LaunchDarkly browser SDK. | ||
*/ | ||
|
@@ -35,12 +37,25 @@ export interface BrowserOptions extends Omit<LDOptionsBase, 'initialConnectionMo | |
* This is equivalent to calling `client.setStreaming()` with the same value. | ||
*/ | ||
streaming?: boolean; | ||
|
||
/** | ||
* Determines if the SDK responds to entering different visibility states to handle tasks such as | ||
* flushing events. | ||
* | ||
* This is true by default. Generally speaking the SDK will be able to most reliably delivery | ||
* events with this setting on. | ||
* | ||
* It may be useful to disable for environments where not all window/document objects are | ||
* available, such as when running the SDK in a browser extension. | ||
*/ | ||
automaticBackgroundHandling?: boolean; | ||
} | ||
|
||
export interface ValidatedOptions { | ||
fetchGoals: boolean; | ||
eventUrlTransformer: (url: string) => string; | ||
streaming?: boolean; | ||
automaticBackgroundHandling?: boolean; | ||
} | ||
|
||
const optDefaults = { | ||
|
@@ -66,8 +81,14 @@ export function filterToBaseOptions(opts: BrowserOptions): LDOptionsBase { | |
return baseOptions; | ||
} | ||
|
||
function applyBrowserDefaults(opts: BrowserOptions) { | ||
// eslint-disable-next-line no-param-reassign | ||
opts.flushInterval ??= DEFAULT_FLUSH_INTERVAL_SECONDS; | ||
} | ||
|
||
export default function validateOptions(opts: BrowserOptions, logger: LDLogger): ValidatedOptions { | ||
const output: ValidatedOptions = { ...optDefaults }; | ||
applyBrowserDefaults(output); | ||
|
||
Object.entries(validators).forEach((entry) => { | ||
const [key, validator] = entry as [keyof BrowserOptions, TypeValidator]; | ||
|
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.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Consolidating adding event handlers resulted in extra parameters for options.