Created
January 5, 2022 06:43
-
-
Save ssv445/8dfef2537a18fb9e496d954ef5d550df to your computer and use it in GitHub Desktop.
Interact to react native wrapper app from your web-app using message passing.
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
function rnIsMobileApp() { | |
// check website open in browser or mobile app | |
return window.ReactNativeWebView !== undefined; | |
} | |
// Returns if a value is a string | |
function rnIsString(value) { | |
return typeof value === 'string' || value instanceof String; | |
} | |
function rnPostMessage(message) { | |
if (rnIsMobileApp()) { | |
//check if it works with iOS | |
if (!rnIsString(message)) { | |
if (message.type !== undefined && message.data != undefined) { | |
message = JSON.stringify(message); | |
} else { | |
console.log( | |
'some error message is not valid {type, data} props needed ', | |
message | |
); | |
} | |
} | |
window.ReactNativeWebView.postMessage(message); | |
} | |
} | |
function rnProcessResponse(onSuccess, onFail, type) { | |
var doc = | |
navigator.userAgent.match(/(iPhone|iPod|iPad)/i) == null ? | |
document : | |
window; | |
doc.addEventListener('message', function(response) { | |
try { | |
response = JSON.parse(response.data); | |
if (response.type == type) { | |
response.status == 200 ? | |
onSuccess(response.message) : | |
onFail(response.message); | |
} | |
} catch (e) { | |
console.error(e, response); | |
} | |
}); | |
} | |
function rnOpenLink(link) { | |
if (rnIsMobileApp()) { | |
var message = { | |
type: 'open_Link', | |
data: link, | |
}; | |
rnPostMessage(message); | |
} else { | |
//for desktop/mobile web open | |
window.location.href = link; | |
} | |
} | |
function rnShareImageIntent(onSuccess, onFail, data) { | |
if (rnIsMobileApp()) { | |
var message = { | |
type: 'share_image_intent', | |
data: data, | |
}; | |
rnPostMessage(message); | |
rnProcessResponse(onSuccess, onFail, 'type_share_image_intent'); | |
} else { | |
//for desktop/mobile web | |
return false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment