ねぎとろ放浪記

ねぎとろ放浪記

個人的備忘録です。勉強したことをまとめていきます。

【React Native】WebViewでのログの出し方

React NativeのWebViewでのログの出力方法のメモ。

injectedJavaScriptonMessage を使う。

ボタンをクリックした時にログを表示するサンプル。
console.log()window.ReactNativeWebView.postMessage() も表示できる。

index.tsx

const debugging = `
    const consoleLog = (type, log) => window.ReactNativeWebView.postMessage(JSON.stringify({'type': 'Console', 'data': {'type': type, 'log': log}}));
    console = {
        log: (log) => consoleLog('log', log),
        debug: (log) => consoleLog('debug', log),
        info: (log) => consoleLog('info', log),
        warn: (log) => consoleLog('warn', log),
        error: (log) => consoleLog('error', log),
    };
`;

const onMessage = payload => {
    let dataPayload;
    try {
        dataPayload = JSON.parse(JSON.stringify(payload.nativeEvent.data));
    } catch (e) {}

    if (dataPayload) {
        if (dataPayload.type === 'Console') {
        console.info(`[Console] ${JSON.stringify(dataPayload.data)}`);
        } else {
        console.log(dataPayload);
        }
    }
};

return (
    <View>
        <WebView
            source={{uri: 'file:///android_asset/index.html'}}
            injectedJavaScript={debugging}
            onMessage={onMessage}
        />
    </View>
    );


index.html

<html>
    <head>
        <title>Sample</title>
    </head>
    <body>
        <h1>This is WebView sample</h1>
        <button id="button1">Button1</button>
        <button id="button2">Button2</button>
        <script type="text/javascript" src="init.js"></script>
    </body>
</html>


init.js

function send_log() {
  console.log('This is log');
}

const button1 = document.getElementById('button1');
button1.addEventListener('click', send_log, false);

function send_log2() {
  window.ReactNativeWebView.postMessage('Hello');
}

const button2 = document.getElementById('button2');
button2.addEventListener('click', send_log2, false);


参考

https://stackoverflow.com/questions/53560744/javascript-console-log-in-a-react-native-webview