Cordova backbutton打破申请

时间:2018-05-25 12:27:18

标签: javascript android cordova

我对基于Angular 5+的Cordova的Android应用程序有疑问。我发现window.history.back()和类似的原生JS返回函数会产生两个问题:

  • 回去时,页面闪烁。它似乎是第一个,所有HTML内容加载并在它之后
  • 在一个关于后退动作的页面中,我的布局被打破(下面的屏幕)

原始观点: Original view

后退按钮: After back button

奇怪的是 - 在改变手机方向后,一切都恢复正常。

我找到了一个解决方案 - 而不是使用我使用Angular Router创建的vanilla JS返回函数:

我订阅路由器的事件并保存所有路线:

this._subs.push(this._router.events.subscribe((e) => {
      if (e instanceof NavigationEnd) {
        this._cordovaService.saveRoute(e.url);
      }
    }));

如果我想要回来,我会使用navigateByUrl函数:

back(): void {
    const lastRoute = this._routingHistory[this._routingHistory.length - 2];
    if (lastRoute) {
      this._router.navigateByUrl(lastRoute);
      this._routingHistory.pop();
    }
  }

为我的inApp后退按钮实现此功能后,一切正常 - 没有闪烁或破坏布局。

虽然在为物理后退按钮实现此功能后,错误是相同的 - 布局中断或闪烁。在我的实施之下:

服务:

this.deviceReady = Observable.fromEvent(document, 'deviceready').publishReplay(1);
    (this.deviceReady as ConnectableObservable<Event>).connect();
    this.restore = Observable.fromEvent(document, 'resume').publishReplay();
    (this.restore as ConnectableObservable<Event>).connect();
    this.backbutton = Observable.fromEvent(document, 'backbutton').publishReplay();
    (this.backbutton as ConnectableObservable<Event>).connect();

使用它:

this._subs.push(this._cordovaService.deviceReady.subscribe(
      () => {
        document.addEventListener('backbutton', function (e) {
          e.preventDefault();
          e.stopPropagation();
          this._cordovaService.back();
        }.bind(this), false);
      }
      )
    );

我确定backbutton中的函数已执行(我已记录了一些信息),但问题仍然存在。

更多信息:

  • 我使用的是cordova版本8.0.0
  • 我正在使用以下插件:

             https://github.com/TheMattRay/cordova-plugin-wkwebviewxhrfix.git“/&gt;          

一些提示:

有一次,我已经构建了Cordova的Android应用程序,这些应用程序运行良好(具有本机JS后退功能),但是在下一次构建之后,所有应用程序都会回来。在hockeyapp中,我看到在良好的工作版本中,最低的Android版本是4.1。在新应用中,它是4.4。

我试图降级Cordova / android引擎版本,但没有任何积极的结果。

此外,我想使用最新的库。

感谢您提供任何帮助。

1 个答案:

答案 0 :(得分:5)

根据以下博客的帖子,我终于找到了解决方案:http://weblogs.thinktecture.com/thomas/2017/02/cordova-vs-zonejs-or-why-is-angulars-document-event-listener-not-in-a-zone.html,在cordova.js导入之前,我在脚本下面添加了以下内容:

   <script>
    (function () {
      'use strict';

      window.addEventListener = function () {
        EventTarget.prototype.addEventListener.apply(this, arguments);
      };

      window.removeEventListener = function () {
        EventTarget.prototype.removeEventListener.apply(this, arguments);
      };

      document.addEventListener = function () {
        EventTarget.prototype.addEventListener.apply(this, arguments);
      };

      document.removeEventListener = function () {
        EventTarget.prototype.removeEventListener.apply(this, arguments);
      };
    })();
  </script>
  <script type="text/javascript" src="cordova.js"></script>

有关为什么会发生此错误的更多信息,您可以在以下GitHub问题中阅读:https://github.com/angular/angular/issues/22509