As more and more clients are asking for mobile apps rather than just responsive websites, the introduction of Ionic has been a fantastic time saver. Moreover, the Ionic Framework has been a lifesaver for app distribution to small businesses with their own apps, bypassing the app store entirely.
However, there are some hurdles that we’ve been running into that have consumed an enormous amount of trial and error. The first one here is the viewing of a remote file by clicking on a common anchor hyperlink. There are a variety of ways to do it, but the problem we ran into that we couldn’t simply add an onclick script to the links. Our customers were typing into a web interface, just as I am right now, and pasting in a link to some pdf files for their employees to read.
For example, the user might be a lineman up on a phone pole and need to review the code regulations for a surge suppresser he is installing. So, the app will have the basic How-To, but when it comes to the details, the instructor has put some reference links in the contents like this http://sitereviewapp.s3.amazonaws.com/pge/Documents/981550045.pdf. That’s great when they’re on a webpage, but on an app, it’s a dead link. You’re being “protected”.
Here’s where we have the issue. The instructor is using a web intranet system to type in all the instructions for the linemen. The Ionic app is downloading the instructions and displaying it like this:
That works great when it’s just generic text with some formatting from a simple editor, but that link? It’s a no go with Ionic.
The first thing is the cordova inappbrowser . With this, we can allow an ionic application to open a new browser window that is pretty easily managed by the client.
But I can’t type a script into a text-editor online (and I wouldn’t ever want them to!) and I can’t include it using innerHTML. So, we need to do it for them. What we’re going to do is run through the file, get the anchor links and add that onclick event.
To do it, we add a HostListener to the component code and, if whatever is clicked on has an href attribute, then cancel that href and open it using the InAppBrowser.
This is clipped directly out of one of our live applications:
public openLink(url:string){ cordova.InAppBrowser.open(url, '_blank', 'location=yes'); } @HostListener('click', ['$event']) onClick(event) { let element: HTMLElement = event.target; let href = element.getAttribute('href'); if (href && href.indexOf('.pdf') !== -1) { event.preventDefault(); this.openLink(element.getAttribute('href')); } }
That’s it.