How to open dynamic links in InAppBrowser?

I have an app where people can post blogs (which may contain links) and also add files that can be downloaded. My need is I would like to open any links that is inside a particular div and those file urls to be opened in InAppBrowser. Is this possible?

Create a function for this purpose.

Psuedo-code it’s something like this:

openLink(url) {
    options = // a bunch of InAppBrowser Options
    InAppBrowser(url, options);
}

I don’t know how it works with Ionic Native, but the concept it’s the same.

Happy coding!

1 Like

@jsalvador
Thanks. So I will have to go through the div to find the links and add (click) method to implement this?.

Yeah, that’s right. Or you can use ng-click for links.

1 Like

@murshid1988
no need to go through all divs containing the link and add a click listener … there is a way, you’re free to use it
first go to your app.html and add a click listener like this

<ion-nav (click)="handleClick($event)" [root]="rootPage"></ion-nav>

and in the app.component add this method

  handleClick(event) {
    if (event.target.tagName == "A") { 
      // open link using inappbrowser
    }
  }

i don’t recommend this way, but if the links you want to open are only one component do the same steps for that component, no need to do it for the whole app, just for the component that shows the links,
hope that helps

3 Likes

@MarcusIII Thanks. Will give it a go :slight_smile:

It works, thanks. For those looking for a more complete code, here is how I did it:

<div class="blog-details">
        <p (click)="handleClick($event)" [innerHtml]="blogsDetails.content | keepHtml"></p>
</div>

Controller:

import { InAppBrowser } from '@ionic-native/in-app-browser';
...
export class BlogDetailsPage {

  constructor(private iab: InAppBrowser) 
  {
    ... 
  }

  handleClick(event) {
    if (event.target.tagName == "A") { 
      this.iab.create(event.target.href, "_system");
      return false;
    }
  }
}

i am getting the url using api and its coming fine with this {{post.post_meta_fields.brand_link}}

but in this not working and giving error < a (click)=“openWithInAppBrowser(’{{post.post_meta_fields.brand_link}}’)” >
so please help
< ion-col ion-item *ngFor=“let post of posts” text-center >
< a (click)=“openWithInAppBrowser(’{{post.post_meta_fields.brand_link}}’)” >
< img style=“width: 50px;margin: 0 auto” height=“50” *ngIf=“post.featured_image_urls && post.featured_image_urls.thumbnail” [src]=“post.featured_image_urls.thumbnail” >
< /a >
< p >{{ post.title.rendered }}< /p >
< /ion-col >

@ankush17

You don’t have to use it like this {{post.post_meta_fields.brand_link}}

Just use post.post_meta_fields.brand_link

So it should be (click)=“openWithInAppBrowser(post.post_meta_fields.brand_link)”