user3715770 user3715770 - 2 months ago 15
HTML Question

I want to redirect to another page if a condition in javascript is true

I am developing a desktop app with Adobe AIR. I want to redirect to another page if internet connection is present, and do nothing if internet connection is not present.

Following is the code I am using for detecting internet connection. The following code displays "Please wait" if internet connection is present, and "Internet connection is unavailable" if internet is not connected.

`

<!doctype html>
<html>
<head>
<script>
function CheckOnlineStatus(msg) {
var status = document.getElementById("status");
var condition = navigator.onLine ? "Please wait" : "Internet connection is unavailable";
var state = document.getElementById("state");
state.innerHTML = condition;
}

function Pageloaded() {
CheckOnlineStatus("load");
document.body.addEventListener("offline", function () {
CheckOnlineStatus("offline")
}, false);
document.body.addEventListener("online", function () {
CheckOnlineStatus("online")
}, false);
}

</script>
<style>
...</style>
</head>
<body onload="Pageloaded()">
<div id="status">
<p id="state">
</p>
</div>
</body>
</html>`


Please suggest required additions or changes to redirect to "http://example.com" if
navigator.onLine
is true.

Answer
if(navigator.onLine){
     window.location.href = "http://example.com";
}

window.location is an object which exists as a property of window. href is a property of window.location which indicates the URL of your current page. You can redirect by assigning a URL to window.location.href.