npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@cniot/react-native-webview-callback

v0.0.6

Published

A lightweight tool library for connecting React Native and webview, providing communication and success and failure callback methods

Downloads

77

Readme

react-native-webview-callback

  • 0.0.6 兼容其他onMessage事件

  • 0.0.5 兼容 devtool 调试时,"react-devtools-bridge" 的事件处理

NPM version NPM downloads

A lightweight tool library for connecting React Native and webview, providing communication and success and failure callback methods

我的博文:实现React Native与内嵌H5相互通信

react-native-webview-callback_01.png

Usage

Import Dependency Package

npm install react-native-webview-callback

Configure and use on H5 end

Define your own methods to provide for React Native calls

You can define your own event API and incorporate it during subsequent initialization. eg(myEvent.ts)

// customH5Api.ts

// Define your own methods to provide for React Native calls
const getWebToken = () => {
  return new Promise((resolve, reject) => {
    try {
      const token = window.localStorage.getItem('token')||'hello';
      resolve(token) // Successful callback
    } catch (error) {
      reject(error)  // Failed callback
    }
  })
};
// other methods

export default {
  getWebToken: getWebToken,
  // other methods
}

Initialize listening in the entry file && Use and get callback

Initialize listening methods in the entry file

import { useEffect, useState } from 'react'
import {
  mergeReactNativeApi,
  useReactNativeAddListener,
  reactNativeCallH5,
} from 'react-native-webview-callback';
import myEvent from './customH5Api';
import './App.css';
function App() {
  useH5AddListener(mergeH5Api(myEvent)) // just need init once ,Entry file
  useEffect(() => {
    window.localStorage.setItem('token', 'mytokenStrXXXXX');// mock data
  },[])
  const [result, setResult] = useState('--');
  const testFn = () => {
    h5CallreactNative({
      methodName: "getAppInfo", // Or other interface functions that you customize on the React Native end, eg:“myReactNativeMethod”
      data: "", // Object data can also be passed, and the specific parameter format depends on the defined interface parameters
    })
      .then((data) => {
        if (typeof data === 'object') {
          setResult(JSON.stringify(data))
        } else if (typeof data === 'string') {
          setResult(data)
        }
        console.log("Successful data:", data);
      })
      .catch((error) => {
        alert("Failed from React Native callback");
        console.error("Failed data:", error);
      });
  }
  return (
    <>
      <h1>H5</h1>
      <div className="card">
        <button onClick={testFn}>
          click to getAPPInfo
        </button>
        <p>
          {result}
        </p>
      </div>
    </>
  )
}

export default App

Configure and use on the React Native end

Define your own methods to provide for H5 calls

You can define your own event API and incorporate it during subsequent initialization. eg(myEvent.ts)

// customNativeApi.tsx
import {
  Platform,
  // Share,
} from 'react-native';
// Define your own methods to provide for H5 calls
const getAppInfo = () => {
  return new Promise((resolve, reject) => {
    try {
      const result = {
        os: Platform.OS,
        version: Platform.Version,
      };
      resolve(result); // Successful callback
    } catch (error) {
      reject(error); // Failed callback
    }
  });
};
// other methods
// const appShare = () => {
//   return new Promise((resolve, reject) => {
//     Share.share({
//       message:
//         'React Native | A framework for building native apps using React',
//     }).then(result => {
//       resolve(result); // Successful callback
//     }).catch(error => {
//       reject(error); // Failed callback
//     })
//   });
// };

export default {
  getAppInfo: getAppInfo,
  // other methods
};

Initialize listening in the entry file & Use and get callback

// App.tsx

import React, {useRef} from 'react';
import {
  SafeAreaView,
  ScrollView,
  Alert,
  StyleSheet,
  Text,
  useColorScheme,
  View,
} from 'react-native';
import {WebView} from 'react-native-webview';
import myEvent from './customNativeApi';
import {
  mergeReactNativeApi,
  useReactNativeAddListener,
  reactNativeCallH5
}  from 'react-native-webview-callback';
const {alert} = Alert;

function App(): JSX.Element {
  const webViewRef: any = useRef(null);
  // 收到消息
  const onMessage = (event: any) => {
    // eslint-disable-next-line react-hooks/rules-of-hooks
    useReactNativeAddListener({
      bridgeReactNativeApi: mergeReactNativeApi(myEvent), // Merge into custom methods on listening objects
      webViewRef,
      event,
    });
  };
  const handleLoadEnd = () => {
    reactNativeCallH5({
      dataParms: {
        methodName: 'getWebToken', //
        data: '',
      },
      webViewRef: webViewRef,
    })
      .then((data: any) => {
        alert(data || 'Successful data:');
        console.log('Successful data:', data);
      })
      .catch(error => {
        console.log('Failed data:', error);
        alert('Failed from H5 callback');
      });
  };

  return (
    <WebView
      ref={webViewRef}
      source={{
        uri: 'http://192.168.1.121:5173',  // Replace with your IP address
      }}
      originWhitelist={['*']}
      allowFileAccess={true}
      onMessage={onMessage}
      onLoadEnd={handleLoadEnd}
      geolocationEnabled={true}
      allowUniversalAccessFromFileURLs={true}
      useWebKit={true}
    />
  );
}

export default App;

examples

You can take a look at the usage examples in react-native-webview-callback-demo

Development

# install dependencies
$ yarn install

# develop library by docs demo
$ yarn start

# build library source code
$ yarn run build

LICENSE

MIT

Copyright (c) 2023 liutao