UNPKG

@tomjs/vscode-webview

Version:

Optimize the postMessage issue between webview page and vscode extension

92 lines (90 loc) 2.94 kB
type PostMessageOptions = PostMessageAsyncOptions & PostMessageDataOptions; interface PostMessageAsyncOptions { /** * the millisecond of try interval time * @default 200 */ interval?: number; /** * the millisecond of post timeout * @default 10000 */ timeout?: number; } interface PostMessageDataOptions { /** * the name of key in the message, default 'type' */ typeKey?: string; /** * the name of data in the message, default 'data' */ dataKey?: string; } type PostMessageListener<T> = (data: T) => void | Promise<void>; /** * A utility wrapper around the acquireVsCodeApi() function, which enables * message passing and state management between the webview and extension * contexts. */ declare class WebviewApi<StateType = any> { private readonly webviewApi; private _options; private listeners; constructor(options?: PostMessageOptions); /** * set the post message options * @param options */ setOptions(options: PostMessageOptions): void; private _postMessage; private _runListener; /** * Post a message to the owner of the webview * @param type the message type * @param data the message content * @param options */ post(type: string | number, data: any | undefined): void; /** * Post a message to the owner of the webview, and return the response. The type of the message to be sent and received must be the same. * @param type the message type * @param data the message content * @param options * @returns */ postAndReceive<T>(type: string | number, data: any | undefined, options?: PostMessageAsyncOptions): Promise<T>; /** * Register a listener for a message type * @param type the message type * @param success the success listener * @param fail the fail listener */ on<T>(type: string | number, success: PostMessageListener<T>, fail?: PostMessageListener<any>): void; /** * Remove a listener for a message type * @param type the message type */ off(type: string | number): void; /** * Post a message to the owner of the webview * @param message the message content */ postMessage<T = any>(message: T): void; /** * Get the persistent state stored for this webview. * * @return The current state or `undefined` if no state has been set. */ getState(): StateType | undefined; /** * Set the persistent state stored for this webview. * * @param newState New persisted state. This must be a JSON serializable object. Can be retrieved * using {@link getState}. * * @return The new state. */ setState<T extends StateType | undefined>(newState: T): T; } export { type PostMessageAsyncOptions, type PostMessageDataOptions, type PostMessageListener, type PostMessageOptions, WebviewApi };