问题
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?
回答1:
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.
来源:https://stackoverflow.com/questions/59009164/timed-popup-with-phonegap-cordova-inappbrowser