简体   繁体   中英

How to inject JavaScript in WebView React Native

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

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);`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM