I have a WebView in my React Native app, and I need to show the logs from the Javascript that is executed within the WebView inside my React Native app.
I think that I need to play around with WebView's nativeConfig
prop to achieve this, but I don't know how to make it work.
Here is my latest attempt:
<WebView
nativeConfig={{
props: {
webContentsDebuggingEnabled: true,
console: new MyLogger()
}
}}
...
class MyLogger {
log = message => {
console.log(message); // Print in RN logs for now...
};
}
Any help would be greatly appreciated.
Writing to the logs in a React Native app works just like in the browser: use console. log , console.
Launch Chrome on your dev computer and navigate to the url chrome://inspect . This page shows you a list of webview instances running on your connected Android device. Click the inspect link next to the webview that you wish to debug. This will open a new Chrome DevTools window for inspecting the webview.
Ok I figured it out after all. I just need to inject some code to the WebView, and have it use my own version of console.
const debugging = `
// Debug
console = new Object();
console.log = function(log) {
window.webViewBridge.send("console", log);
};
console.debug = console.log;
console.info = console.log;
console.warn = console.log;
console.error = console.log;
`;
<WebView
injectedJavaScript={debugging}
onMessage={this.onMessage}
I then get the console logs inside the onMessage function.
If you're using Webview v5 or above, then you can use something similar to this:
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(payload.nativeEvent.data);
} catch (e) {}
if (dataPayload) {
if (dataPayload.type === 'Console') {
console.info(`[Console] ${JSON.stringify(dataPayload.data)}`);
} else {
console.log(dataPayload)
}
}
};
<WebView
injectedJavaScript={debugging}
onMessage={onMessage}
/>
The difference from the accepted question is that webview changed how you post message. More here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With