【问题标题】:Check if inappbrowser open or closed检查inappbrowser是打开还是关闭
【发布时间】:2017-10-05 14:28:31
【问题描述】:

在我的科尔多瓦应用程序中,我正在通过以下代码在 inappbrowser 中打开(使用 InAppBrowser 插件)一个网页。

var ref = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
ref.close();

现在我想在ref.isClosed() 之类的 js 中检查 InAppBrowser 是否已关闭(不是我想检查浏览器本身打开或关闭的特定 URL)。但是 InAppBrowser 不支持这样的功能。有什么办法可以找到吗?

【问题讨论】:

    标签: javascript html cordova inappbrowser


    【解决方案1】:

    您可以创建一个简单的包装器来跟踪它是打开还是关闭,例如:

    var iab_controller = (function(){
        var ref, isOpen = false;
    
        return {
            open: function(url){
                ref = cordova.InAppBrowser.open(url, '_blank', 'location=yes');
                isOpen = true;
                return ref;
            },
            close: function(){
                if(isOpen){
                    ref.close();
                    ref = null;
                    isOpen = false;
                }
            },
            isOpen: function(){
                return isOpen;
            },
            isClosed: function(){
                return !isOpen;
            }
        };
    
    })();
    
    console.log("isOpen: " + iab_controller.isOpen())
    console.log("isClosed: " + iab_controller.isClosed())
    
    iab_controller.open('http://apache.org');
    
    console.log("isOpen: " + iab_controller.isOpen())
    console.log("isClosed: " + iab_controller.isClosed())
    
    iab_controller.close();
    
    console.log("isOpen: " + iab_controller.isOpen())
    console.log("isClosed: " + iab_controller.isClosed())
    

    【讨论】:

    • 这是一个不错的解决方案。但是return ref; 将返回cordova.InAppBrowser 类型的对象。那我怎么打电话给iab_controller.isOpen()。对吗?
    • iab_controller.open 将返回一个 cordova.InappBrowser 对象以防你想要引用它,但 iab_controller 本身是一个单例,所以你只需调用 var iabRef = iab_controller.open(url); iab_controller.isOpen();
    • 不返回控制器引用。所以它正在抛出Uncaught TypeError: win.isOpen is not a function
    • 非常感谢。我对您的包装器进行了一些更改,使其像cordova.InAppBrowser 一样工作。感谢您的帮助:)
    【解决方案2】:
    var browserRef = cordova.InAppBrowser.open('http://apache.org', '_blank', 'location=yes');
    var isOpen = true;
    
    browserRef.addEventListener('exit', function(event) {
      console.log('exit: event fires when the InAppBrowser window is closed.');
      isOpen = false;
    });
    

    为 InAppBrowser 的退出事件添加侦听器。这将允许您执行逻辑或设置变量来管理状态。

    https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/#inappbrowseraddeventlistener

    【讨论】:

    • 谢谢。它甚至工作简单。但我使用DaveAlden 的答案使其更易于访问和定制。感谢任何方式:)
    • 'exit' 事件正是我所寻找的。 +1
    猜你喜欢
    • 1970-01-01
    • 2018-11-09
    • 2011-10-20
    • 2013-03-11
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多