capacitor-inappbrowser icon indicating copy to clipboard operation
capacitor-inappbrowser copied to clipboard

Webview and Ionic Communication

Open jeanpfs opened this issue 10 months ago • 3 comments

Hello, is there any way to capture a message from the webview?

In React Native, I can do something like the code below, but I couldn't find a solution for this in your library.

const INJECTED_JAVASCRIPT = `(function() {
    window.ReactNativeWebView.postMessage(JSON.stringify({key : "value"}));
})();`;



<WebView
  source={{ uri: 'https://reactnative.dev' }}
  injectedJavaScript={INJECTED_JAVASCRIPT}
  onMessage={(event) => {
       const data = JSON.parse(event.nativeEvent.data);
       alert(data.key);
  }}
/>;

jeanpfs avatar Apr 04 '24 19:04 jeanpfs

Hi. This plugin doesn't know how to work with postMessage. Here is a similar issue https://github.com/Cap-go/capacitor-inappbrowser/issues/84

korenskoy avatar Apr 16 '24 08:04 korenskoy

This could be done pretty fast. You can support it here: https://console.algora.io/bounties/new

riderx avatar Jul 02 '24 18:07 riderx

A workaround that I developed in cordova webview was reading local storage. Now I preferred using directly a websocket (using pusher)

xam8re avatar Jul 25 '24 14:07 xam8re

Hello, I needed the feature for my last project, so I made it in 6.4.3 You can now post messages from inappbrowser like that:

window.mobileApp.postMessage({ "detail": { "message": "myMessage" } })

And listen to it from the Capacitor webview with

InAppBrowser.addListener('messageFromWebview', (event) => {
  console.log('messageFromWebview', event)
})

Both ways were implemented. To do the reverse from Capacitor webview

    InAppBrowser.postMessage({
      detail: {
        status: 'ok4',
      },
    })

And listen in the inappbrowser:

  window.addEventListener('messageFromNative', (event: CustomEvent) => {
    const message = event.detail
    console.log('Received message from native:', message)
    // Handle the message here
    // For example, you could update some state or trigger an action
  })

riderx avatar Aug 30 '24 04:08 riderx

This seems not to work, I get window."mobileApp" undefined inside browser page... Using v6.6.8

@riderx any breaking changes here ?

EDIT: it is working on iOS device but not on Android

akships avatar Oct 03 '24 09:10 akships