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

2

7

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;
        }
      };
    }
Costly answered 9/1, 2020 at 5:18 Comment(0)
C
5

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

"server": {
  "allowNavigation": [
    "*"
  ]
}
Comatose answered 26/3, 2021 at 14:54 Comment(0)
B
3

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>
);
Bibcock answered 15/7, 2020 at 8:58 Comment(2)
Why does it not allow opening pdf file ?Backsword
Browser.open allow to open direct link but not base64 or data uriPattipattie

© 2022 - 2024 — McMap. All rights reserved.