Reputation: 792
I have different types of scripts that need to be executed through WebView in the app. I followed many other related posts, but those didn't help me much. The first one is executing fine.
setTimeout(function() {
window.ReactNativeWebView.postMessage(JSON.stringify(${window.CartVue.carts}))
}, 2000);true;
For the second one, can someone help me execute the below JavaScript code in WebView?
async function extractItems(){
const responsePromise = await fetch('https://www2.hm.com/tr_tr/v1/carts',
{
credentials: 'include'});
const response = await responsePromise.json();
return response;
}
await extractItems();
WebView
<WebView
ref={webViewRef}
source={{uri: webUrl}}
onNavigationStateChange={webViewState => {
// setWebUrl(webViewState?.url);
}}
javaScriptEnabled={true}
domStorageEnabled={true}
startInLoadingState={true}
injectedJavaScript={jsCode}
onLoadEnd={() => onLoadWebUrl()}
renderLoading={() => <Loading visible />}
onError={() => webViewRef.current.reload()}
onMessage={event => {
console.log("onMessage event ==> ",);
if (cartUrl !== '') {
onMessage(event);
}
}}
/>
Upvotes: 1
Views: 3579
Reputation: 792
After struggling I found the solution for second script. I am using below piece of code for second script to run. Hope it may help others.
const jsCode = `setTimeout(() => {
const extractCart = async () => {
async function extractItems() {
const responsePromise = await fetch('https://www2.hm.com/tr_tr/v1/carts', {
credentials: 'include',
});
const response = await responsePromise.json();
return response;
}
const res = await extractItems();
window.ReactNativeWebView.postMessage(JSON.stringify(res));
};
extractCart();
}, 2000);`;
Upvotes: 3