简体   繁体   English

如何在 WebView React Native 中注入 JavaScript

[英]How to inject JavaScript in WebView React Native

I have different types of scripts that need to be executed through WebView in the app.我有不同类型的脚本需要通过应用程序中的 WebView 执行。 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?对于第二个,有人可以帮我在 WebView 中执行以下 JavaScript 代码吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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