androidcordovawebkitcordova-pluginsinappbrowser

webkit is not defined : InAppBrowser Cordova


I am running an InAppBrowser instance from typescript file in Cordova application. I have the latest InAppBrowser plugin hooked in my package.json. When I add listener on loadStop event of this InAppBrowser. It doesn't execute script saying 'webkit is not defined'. I am not able to find answers related to it. Does any body know how to resolve this?

Code Snippet

      switchHybridApp.on("loadstop").subscribe((event: InAppBrowserEvent) => {
      console.log("Here I am 3");
      console.log('loadstop has been fired'); // this fires
      debugger;
        // when this has been executed, `webkit` variable doesn't exist inside of the `inappbrowser`
        // instance
        switchHybridApp.executeScript({ code: "\
        var message = 'this is the message';\
        var messageObj = {my_message: message};\
        var stringifiedMessageObj = JSON.stringify(messageObj);\
        webkit.messageHandlers.cordova_iab.postMessage(stringifiedMessageObj);"
      });
      }
  );

Error Error

Solutions I tried which didn't work out

(window as any).webkit....

( window).webkit....


Solution

  • Okay, I am here after a year to answer this question and how I solved it. So I had infinite running interval to check localStorage of native and inappbrowser using executeScript, but that was a pretty bad option. Now that InAppBrowser has 'postMessage' implemented. Its very simple communication now.

    What I did is, web app I opened inside inAppBrowser, I ran this in my ts file.

    (window as any).webkit.messageHandlers.cordova_iab.postMessage(sendToNative);
    

    note that, objToSend must be a JSON object. Passing a simple string won't work.

    you can create object something like this -

    const sendToNative= 'frontCameraOpen';
    const sendToNative= {message: sendToNative};
    const stringifiedMessageObj = JSON.stringify(sendToNative);
    

    Now from native side, use this eventlistner like

    inAppBrowser.on('message').subscribe((dataFromIAB) => {
          alert(dataFromIAB.data.sendToNative);
    });
    

    Thanks @DaveAlden for this feature, I was doing it wrong a year ago lol.