Skip to content

Commit 795a49a

Browse files
committed
Fix android postMessage and cross-origin webview
1 parent cf43ad3 commit 795a49a

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

iframe.html

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,20 @@
5454
} = JSON.parse(UrlQueryData);
5555

5656
function sendMessageToRN(msg) {
57-
window.ReactNativeWebView.postMessage(JSON.stringify(msg));
57+
58+
if (window.ReactNativeWebView) {
59+
// React Native WebView
60+
window.ReactNativeWebView.postMessage(JSON.stringify(msg));
61+
} else if (window.parent) {
62+
// This is from expo web iframe.
63+
//
64+
// We set cross origin to so that this will work on differnet origin.
65+
// We don't expect any sensitive data to be sent.
66+
window.parent.postMessage(JSON.stringify(msg), '*');
67+
} else {
68+
console.error('Not running in Iframe, cannot postMessage.');
69+
return;
70+
}
5871
}
5972

6073
let metaString = '';
@@ -147,7 +160,14 @@
147160
document.addEventListener('mozfullscreenchange', onFullScreenChange);
148161
document.addEventListener('webkitfullscreenchange', onFullScreenChange);
149162

150-
window.addEventListener('message', function (event) {
163+
const userAgent = navigator.userAgent;
164+
const isAndroidWebView = userAgent.includes('Android') && userAgent.includes('; wv');
165+
166+
// NOTE: for Android Webview, postMessage needs to be set on document
167+
// instead of window.
168+
// https://github.com/react-native-webview/react-native-webview/issues/356
169+
const listenerDocument = isAndroidWebView ? document : window;
170+
listenerDocument.addEventListener('message', function (event) {
151171
const {data} = event;
152172

153173
try {

src/YoutubeIframe.js

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,10 @@ const YoutubeIframe = (props, ref) => {
6262
}
6363

6464
const message = JSON.stringify({eventName, meta});
65-
webViewRef.current.postMessage(message);
65+
66+
// NOTE: we set cross origin to so that this will work for webView for
67+
// website hosted across different origin.
68+
webViewRef.current.postMessage(message, '*');
6669
},
6770
[playerReady],
6871
);
@@ -193,6 +196,14 @@ const YoutubeIframe = (props, ref) => {
193196
break;
194197
case 'playerStateChange':
195198
onChangeState(PLAYER_STATES[message.data]);
199+
if (message.data === -1) {
200+
// unstartred state is -1
201+
// We will not normally "change" to this state, but it can happen
202+
// if autoplay is not supported.
203+
console.warn(
204+
'[rn-youtube-iframe] Player unstarted - autoplay may be blocked.',
205+
);
206+
}
196207
break;
197208
case 'playerReady':
198209
onReady();

0 commit comments

Comments
 (0)