Skip to content Skip to sidebar Skip to footer

How To Call A Function From A Button Click In An Inappbrowser Back In Ionic App?

I have an ionic app in which I am trying to call a method which calls for an InAppBrowser. The browser instance is saved in a local variable and used to call executeScript to inser

Solution 1:

You could include deeplinks to your project and call a window.open(yourcustomUrl) and you will be redirected back to your app

Solution 2:

Upon research I was able to achieve the functionality:

We have to use post message from in-app-browser to listen to events in inAppBrowser and using message event on inAppBrowser we can capture the message in our ionic app side.

The Code in HTML file:

<ion-button (click)="openWebpage()">Open InAppBrowser</ion-button>

The Code in TS file:

openWebpage() {
    let browser = this.iab.create('https://www.google.com/', '_blank'
      , {
        closebuttoncolor: "#ffffff",
        lefttoright: 'yes',
        hideurlbar: 'yes',
        fullscreen: 'yes',
        hardwareback: 'no',
        toolbarcolor: '#145a7b',
        zoom: 'no',
        useWideViewPort: 'no',
        hidenavigationbuttons: 'yes',
        footer: 'no',
        message: "Hello",
        toolbar : 'no',
        location: 'no'
      }
    );

    browser.on('loadstop').subscribe(() => {
      browser.executeScript({ code: "(function() { var body = document.querySelector('body'); var button = document.createElement('div'); button.innerHTML = 'Header'; button.classList.add('header'); body.appendChild(button);  })();" });
      browser.executeScript({ code: "(function() { var body = document.querySelector('body'); var button = document.createElement('div'); button.setAttribute('id','customBackbtn');button.innerHTML = '< Back'; button.classList.add('back_btn'); button.onclick = function () { }; body.appendChild(button);  } )(   );" },);
      browser.executeScript({
        code: "document.getElementById('customBackbtn').onclick = function() {\
        var message = 'close';\
            var messageObj = {message: message};\
            var stringifiedMessageObj = JSON.stringify(messageObj);\
        webkit.messageHandlers.cordova_iab.postMessage('stringifiedMessageObj');\
      }"});
    
      browser.insertCSS({ code: ".header {position: absolute;font-size: 22px;top: 0px;left: 50%;transform: translate(-50%);display: flex;justify-content: center;align-items: center ;height: 75px;color: white;background: #145a7b;width: 100%;} .back_btn {  text-decoration: underline;position: absolute; display:flex;align-items: center;height: 75px;font-size: 22px; top: 0px; left: 20px;color:#FFFFFF } #myvoya-sso-ui {padding-top: 75px;}" });
    });

    browser.on('message').subscribe((val)=>{
      constpostObject:any = val;
      if(postObject.data.message == 'close'){
         browser.close();
      }
    });
  }

Post a Comment for "How To Call A Function From A Button Click In An Inappbrowser Back In Ionic App?"