Home > Software engineering >  react-native webview accessing variabels and functions directly
react-native webview accessing variabels and functions directly

Time:11-16

i have a simple website with a toggle function that toggles some data.

<body>
  <h1>customerType: <span id="h1_element"></span></h1>
  <script>
    let customerType = "Public"
    function toggle(){
      customerType = (customerType === "Public") ? "Private" : "Public"
      document.getElementById("h1_element").innerText = customerType;
    }
    toggle()
  </script>
</body>

i then have a react-native app that can toggle the data and display the new data.

export default function Inject() {
  const [customer, setCustomer] = React.useState('-');
  const viewRef = React.useRef();

  const postCustomer = () => viewRef.current.injectJavaScript('window.ReactNativeWebView.postMessage(customerType)');

  const toggleCustomer = () => {
    viewRef.current.injectJavaScript('toggle()');
  }

  return (
    <SafeAreaView style={{ flex: 1, top: 50 }}>
      <Text>WebView data: {customer}</Text>
      <Button onPress={toggleCustomer} title="toggle webView data" />
      <WebView 
        ref={viewRef}
        source={{ uri: 'localhost' }} 
        onMessage={ event => setCustomer(event.nativeEvent.data) }
        javaScriptEnabledAndroid={ true }
        onl oadEnd={ postCustomer }
      />
    </SafeAreaView>
  );
}

I can access the function by simply using refName.current.injectJavaScript('funcName()'), but how could you access the function big project with many modules with their own script files and maybe even same function names?

I guess one way is to make the function global and then access it by window.funcName(), or bind it to a button element and then find the button with a queryselector, but is there a more direct way?

CodePudding user response:

Create objects in window per functionality. Something like this:

window.test = { foo: 'bar', print: () => console.log('foobar') }

or maybe one top level object for the app to keep things clean

window.myApp = { 
  first: { foo: 'bar', print: () => console.log('foobar') },
  second: { foo: 'bar', print: () => console.log('foobar') } 
}
  • Related