Skip to content Skip to sidebar Skip to footer

Angular Marked And Inappbrowser Opening All Links In The System Browser

I am working on an Ionic app where users can post markdown content. In order to make this work, I am using the angular-marked library. In the app, I want all markdown links to be o

Solution 1:

There are two problems with your code

1. the name of an angular directive should be in camelCase, it will be converted to kebab-case in HTML. This is very easy to fix, just change

 .directive('fab-extLink', ['$cordovaInAppBrowser', function($cordovaInAppBrowser){

to

 .directive('fabExtlink', ['$cordovaInAppBrowser', function($cordovaInAppBrowser){

2. in your case, there is <a fab-extlink> in your HTML, but angular doesn't $compile (instantiate) it.

This is a difficult one (if you don't want to monkey-patch angular-marked).

angular-marked uses element.html(marked(text, scope.opts || null)); to set the inner HTML of the element, it skips angular's compiling process, so directives aren't initialized..

One workaround is to use a global function (not elegant I know):

Define it in app.run:

.run(function ($cordovaInAppBrowser) {
  window.openInSystemBrowser=function(link){
     $cordovaInAppBrowser.open(link, '_system');
  };

and config angular-marked to use onclick, so that it works independent of angular.

markedProvider.setRenderer({
        link: function (href, title, text) {
          return'<a onclick="openInSystemBrowser(\'' + href + '\')"' + (title ? ' title="' + title + '"' : '') + '>' + text + '</a>';
        }
      });

The other way I can think of is to fork and patch angular-marked.


The monkey-patch solution:

  1. Open angular-marked.js
  2. replace

    element.html(marked(text, scope.opts || null));
    

    with

    element.replaceWith($compile(marked(text, scope.opts || null))(scope));
    

update2

I checked the repo, the newest version of angular-marked (v1.2) supports an attribute called compile, to do exactly that.

e.g.

<marked compile="true">
          # Markdown [Google](http://www.google.com)
          *It works!*
</marked>

So, in conclusion..


TLDR version

1. change

 .directive('fab-extLink', ...

to

 .directive('fabExtlink', ...

2. add attribute compile='true' to <marked> directive

Solution 2:

If you are looking for a easy way to open links in native browsers on mobile devices with marked can you just try setting this in your angular .config:

markedProvider.setRenderer({
  link: function(href, title, text) {
    return"<a href='" + href + "'" + (title ? " title='" + title + "'" : '') + " onclick='window.open("+href+", '_system')'" + " target='_system'>" + text + "</a>";
  }
});

And then you would need to bind an onDeviceReady function somewhere like this:

document.addEventListener('deviceready', onDeviceReady, false);

functiononDeviceReady() {
  window.open = cordova.InAppBrowser.open;
}

Post a Comment for "Angular Marked And Inappbrowser Opening All Links In The System Browser"