How do I open all links in Capacitor's In-App Browser?

I want to configure Capacitor to open all links like:

<a href="https://www.google.com" target="_blank">Google Link</a>

within Capacitor's In-App Browser feature. I know I can open it by using the open() Method of the Browser API, but some of my HTML content (and so it's links) are coming from the database. Currently on iOS and Android, my apps open the link above with an external Browser such as Safari.

Sources:

https://capacitor.ionicframework.com/docs/apis/browser

Edit - My current solution which I do not really like:

    if (this.$q.platform.is.capacitor) {
      document.onclick = function(event: any): boolean | void {
        const element: any = event.target || event.srcElement;

        if (element.tagName === 'A' && element.target === '_blank' && element.href) {
          event.preventDefault();
          Browser.open({ url: element.href });
          return true;
        }
      };
    }

Upvotes: 7

Views: 17501

Answers (2)

If you want not to "exit" to an external browser maybe you just need to add to the capacitor.config.json:

"server": {
  "allowNavigation": [
    "*"
  ]
}

Upvotes: 6

Lindstrom
Lindstrom

Reputation: 815

Here is a basic version of what I use (react):

// override window.open

import {
  Capacitor,
  Plugins,
} from '@capacitor/core';

const { Browser } = Plugins;

if (Capacitor.isNative) {
  window.open = async url => Browser.open({ url });
}
// custom component that links

const { label, link, onClick } = props;
const handleClick = (e) => {
    if (link) {
      window.open(link, '_blank');
    } else if (onClick) {
      onClick(e);
    }
  };
return (
  <div onClick={handleClick}>{label}</div>
);

Upvotes: 3

Related Questions