1

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);
    }
  }}
/>

1 Answer 1

3

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);`;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.