简体   繁体   中英

Timed popup with PhoneGap/Cordova InAppBrowser?

I'm using PhoneGap (Apache Cordova) with the InAppBrowser plugin (cordova-plugin-inappbrowser). In order to display a popup window, I'm using the following function:

function popup(url) {
  var win = cordova.InAppBrowser.open(url, "_blank", "location=no");
  win.addEventListener("loadstop", function() {
    var loop = window.setInterval(function() {
      win.executeScript(
        {code: "window.shouldClose"},
        function(values) {
          if(values[0]) {
            win.close();
            window.clearInterval(loop);
          }
        }
      );
    }, 200);
  });
}

What I really need is a function whose spec is:

function Popup(url, maxTimeToWaitIfResponseIsSlow)

Any ideas how to achieve this?

So I've found an answer after some research and testing. Here is the modified function, with "double defense" in the client side:

function popup(url) {
  var elapsed = 0;
  var loadstopFired = false;
  var win = cordova.InAppBrowser.open(url, "_blank", "location=no");
  setTimeout(function() {if (!loadstopFired) win.close();}, 2000);
  win.addEventListener("loadstop", function() {
    loadstopFired = true;
    var loop = window.setInterval(function() {
      elapsed += 200;
      win.executeScript(
        {code: "window.popupStatus"},
        function(values) {
          if (values[0]=="closed") { win.close(); window.clearInterval(loop); }
          else if ((values[0]!="loaded") && (elapsed>2000)) { win.close(); window.clearInterval(loop); }
        }
      );
    }, 200);
  });
}

While the server side (the url called) looks like:

...
<body onload="window.popupStatus='loaded';">
  ...
  <img src="close.png" onclick="window.popupStatus='closed';" />
  ...
</body>
...

Any comment appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM