@@ -14,6 +14,7 @@ export type WebViewStreamArgs = {
1414 name : string ;
1515 target : string ;
1616 getWebView : ( ) => Promise < WebViewInterface > ;
17+ btoa ?: ( data : string ) => string ;
1718} ;
1819
1920/**
@@ -26,6 +27,8 @@ export class WebViewMessageStream extends BasePostMessageStream {
2627
2728 #webView: WebViewInterface | undefined ;
2829
30+ #btoa?: ( data : string ) => string ;
31+
2932 /**
3033 * Creates a stream for communicating with other streams inside a WebView.
3134 *
@@ -34,12 +37,14 @@ export class WebViewMessageStream extends BasePostMessageStream {
3437 * multiple streams sharing the same window object.
3538 * @param args.target - The name of the stream to exchange messages with.
3639 * @param args.getWebView - A asynchronous getter for the webview.
40+ * @param args.btoa - An optional function that encodes a string to base64.
3741 */
38- constructor ( { name, target, getWebView } : WebViewStreamArgs ) {
42+ constructor ( { name, target, getWebView, btoa } : WebViewStreamArgs ) {
3943 super ( ) ;
4044
4145 this . #name = name ;
4246 this . #target = target ;
47+ this . #btoa = btoa ;
4348
4449 this . _onMessage = this . _onMessage . bind ( this ) ;
4550
@@ -58,6 +63,15 @@ export class WebViewMessageStream extends BasePostMessageStream {
5863 } ) ;
5964 }
6065
66+ #encodeMessage( json : string ) : string {
67+ if ( this . #btoa) {
68+ return this . #btoa( json ) ;
69+ }
70+
71+ const bytes = stringToBytes ( json ) ;
72+ return bytesToBase64 ( bytes ) ;
73+ }
74+
6175 protected _postMessage ( data : unknown ) : void {
6276 assert ( this . #webView) ;
6377 const json = JSON . stringify ( {
@@ -67,9 +81,7 @@ export class WebViewMessageStream extends BasePostMessageStream {
6781
6882 // To prevent XSS, we base64 encode the message before injecting it.
6983 // This adds significant performance overhead.
70- // TODO: Should we use mobile native base64 here?
71- const bytes = stringToBytes ( json ) ;
72- const base64 = bytesToBase64 ( bytes ) ;
84+ const base64 = this . #encodeMessage( json ) ;
7385 this . #webView. injectJavaScript ( `window.postMessage('${ base64 } ')` ) ;
7486 }
7587
0 commit comments