在ionic應用中打開外部網站(使用InAppBrowser插件)

在安卓上試了一下,如果直接window.open(url), 在app中點擊外部鏈接沒有任何反應。

 

安裝https://github.com/apache/cordova-plugin-inappbrowser
執行命令:
ionic plugin add cordova-plugin-inappbrowser

簡而言之,就是用window.cordova.InAppBrowser.open替換window.open

 

步驟:

1. 在應用程序啓動的時候判斷window.cordova是否存在如果是重寫window.open方法

 

2. 用ng-click="openLink(story.url)" 替換先前的href

 

3. 在$scope中定義openLink方法。

4.  連上手機, 運行ionic run android測試 

文件一: www/index.html

<div class="list">
      <a ng-click="openLink(story.url)" class="item item-thumbnail-left item-text-wrap"
         ng-repeat="story in stories track by story.id">
        <img ng-src="{{story.thumbnail}}" ng-if="story.thumbnail.startsWith('http')"/>
 
        <h2>{{story.title}}</h2>
 
        <p>
          <span am-time-ago="story.created_utc" am-preprocess="unix"></span> - {{story.domain}}
        </p>
      </a>
    </div>

 文件二: www/js/app.js

(function () {
  var app = angular.module('myreddit', ['ionic', 'angularMoment']);
  app.controller('RedditCtrl', function ($http, $scope) {
    $scope.stories = [];
 
    function loadStories(params, callback) { 。。。
    }
 
    $scope.loadOlderStories = function () {。。。
    }
 
    $scope.loadNewerStories = function () {。。。
    }
 
    $scope.openLink = function (url) {
      window.open(url, '_blank');
    }
 
  });
  app.run(function ($ionicPlatform) {
    $ionicPlatform.ready(function () {
     。。。
      if (window.cordova && window.cordova.InAppBrowser) {
        window.open = window.cordova.InAppBrowser.open;
      }
。。。
    });
  })
 
})();

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章