• Register
Welcome to Kodlogs Q&A, programming questions and answer website.

Most popular tags

java program python php javascript android c# r spring c mysql eclipse arrays python-3 exception tomcat ggplot2 spring-boot numpy html sql-server jdbc ssl sockets windows string x python-2 hibernate 7 java-8 intellij-idea ssl-certificate entity-framework macos pandas minecraft ios csv security sql json asp list net class heap-memory for-loop scikit-learn winforms illegalstateexception keytool matlab redirect code program junit pip maven ubuntu loops math facebook datetime jquery cryptography loop int import https tsql fatal-error struts java-applet spring-mvc runtime-error apache-spark pyspark garbage-collection amazon-web-services sql-server-2005 quirks-mode internet-explorer-9 internet-explorer reporting-services anova machine-learning keras indentation-error unit-testing android-studio jupyter-notebook glmnet virtualenv webclient visual-studio-2010 webpack compiler-errors numpy-ndarray curl vagrant aspnet reporting dataframe nullpointerexception javafx tensorflow jsp django jpa docker wordpress servlet indentation xcode typeerror scanner sum deployment socketexception git linux certificate css util oracle cmd node recursion search tcp syntax connection float httpwebrequest js main function number file html5 spring-data-jpa softmax elastic-beanstalk google-sheets-api google-spreadsheet-api cnf minidump xuggler acumatica gitlab elasticsearch-5 elasticsearch app-transport-security ios10 ios9 cdn cloudflare wampserver plpgsql salt-stack sysv parent-child android-edittext textview visual-studio-2012 android-workmanager unique-index unity2d unity3d electron theano maven-compiler-plugin pickle assetbundle rstudio bar-chart python-tesseract tomcat6 primefaces solr easymock jvm-crash tomcat7 apache-httpclient-4 web-services woodstox discord jersey-2 prepared-statement resultset sencha-cmd sencha-touch-2 sencha-touch powermock fips apex x509certificate ibm-bpm websphere-7 file-permissions file-io accesscontrolexception grizzly atmosphere slick2d lwjgl informetica twitter-bootstrap-3 jax-rs resteasy spring-security-kerberos spring-security kerberos long-integer mapnik pytorch git-review vpython continuation homebrew xgboost conda visual-studio android-asynctask stack-trace user-interface jaxws-maven-plugin maven-3 maven-2 browser-notsupportedexception google-maps-api-3 google-maps visual-studio-code truststore firebase-authentication aws-organizations php-7 string-formatting cplusplus visual-studio-2015 net-core net-mvc msbuild extension-methods foreign-keys windows-services react-redux reactjs inputstream facebook-graph-api entity-framework-4 reportingservices-2005 mips linear-regression deep-learning block-device melt reshape2 floating-point webpack-dev-server javascrip 0-lollipop android-5 statsmodels avx eclipseide javafx-2 php-not-recognized laravel command-line tinyurl classnotfoundexception atom-editor android-emulator android-sdk-tools ionic2 cordova foobar2k tcplistener net-2 net-4 ole-db-provider export-to-excel openrowset windows-10 vagrantfile jvm-arguments global-variables orm autopostback classformatexception eof upstart qt ipv4 graphviz pydot atom curses unityeditor pandoc tesseract xls oledb redux spotify cxf wamp nio stacked prediction headless hyperlink outlook jackson keystore applicationcontext pipeline iis jstl encryption perfect-square objective-c carthage xcode8 indexing standard-deviation sudo xampp postgresql connector apple mdf kubernetes destructor gettime arithmeticexception gmail ioexception heuristics milliseconds disk cpu npm modx-revolution goldsky modx prevnext javascript-dictionary stack-smashing device-monitor radio-button android-actionbaractivity android-activity android-fragments java-long unqualified-id ora-12154 javc c++ java nullpointerexception runtime-error drjava awt-eventqueue dsx math-pow ajquery nosuchelementexception appcompatactivity jsf jtextfield awt jpanel inputmismatchexception glassfish deque jupyter flask lvalue gradle servlets netbeans simulation ibm factorial javax apache boot opengl virtualbox jvm margins 2147483647 mongodb cloud firebase plot plugins github processor automation crash card pointers editor concatenation formatting debugging devices module testing color arraylist sequence nested date caching expected build response ip directory algorithms release collections print figure casting url expression validation integer microsoft sorting sort read types replace rest ajax exe excel dictionary message required database text variable time size dll system files table runtime static random code web map http error version 0 2 my
0 votes
14 views
How do you redirect a page to another page in JavaScript on page load?  I am required to redirect to another page when page loads , how do i do this? I want to see full code if anyone can provide?
by (930 points)  

2 Answers

0 votes

Redirect to another page on load using JavaScript

Javascript redirect on page load

You can use server-side redirects, HTML meta refresh redirects and JavaScript redirects to redirect a page to another page in Javascript.

Lets see this through some examples to redirect a page using Javascript.

User does not appreciate experience if their are interruptive or unexpected web page redirects, as this will cause frustration and annoyance to users.

For instance, in the event that you divert the clients to another site when they arrive on your site, that will clearly cause disappointment for them. Additionally, in the event that you take the clients to an unessential page after a clock, after they click on a catch or picture, or after they complete a specific activity on your site, that will most likely bring about the client needing to leave your site on the double and never return.

Another reason you ought to keep away from redirect where conceivable is that the web search tools don't support sites that utilization diverts, particularly in the event that they are misleading. Your webpage may even get expelled from their file on the off chance that you have diverts on your site that attempt to deceive the web index bots or that outcome in an awful client experience. Having said that, there are additionally a few situations where a divert can be very helpful dependent on the setting of your site page or a particular element of your web application and we will leave the choice whether to utilize a divert or not, to you.

Lets now see how JavaScript redirects work.

JavaScript Redirect Methods

Some of redirect useful methods:

// used for new location of the current window.

window.location = "https://www.kodlogs.com";

// used for the new href (URL) for the current window.

window.location.href =  "https://www.kodlogs.com";

// used for a new URL to the current window.

window.location.assign("https://www.kodlogs.com";);

//used for replacing the location of the current window with the new one.

window.location.replace("https://www.kodlogs.com";);

// used for the location of the current window itself.

self.location =  "https://www.kodlogs.com";;

// used for the location of the topmost window of the current window.

top.location =  "https://www.kodlogs.com";;

JavaScript Redirect: Redirect to another Page on Page Load

<script>

  window.location.href = "https://www.kodlogs.com";

</script>

JavaScript Redirect: Redirect the another Page After a some time or Period

<script>

setTimeout(function() {

  window.location.href = "https://www.kodlogs.com";

}, 9000);

</script>

JavaScript Redirect: Redirect the Page After an Event or User Action

<script>

// Check if the condition is true and then redirect.

if ( ... ) {

  window.location.href = "https://www.kodlogs.com";

}

</script>

// onclick event is assigned to the #button element.

document.getElementById("button").onclick = function() {

  window.location.href = "https://www.kodlogs.com";

};

</script>

Conclusion:

So we have seen in illustration above how JavaScript redirect is used . The above code could be helpful for  you while handling your web page redirects.

by (930 points)  
edited by
0 votes

Some javascript methods to do page redirect to another page on load:

Redirect Javascript part:

window.onload = function() {

    window.location.href = "http://somedomain.com";

}

window.onload = function() {

 window.location.replace("http://somedomain.com");

}

HTML Part:

<html>

  <head>

    <meta http-equiv="refresh" content="0;url=http://somedomain.com" />

    <title></title>

  </head>

 <body></body>

</html>

Another way is to use onload event in body tag of HTML

<html>

  <head>

    <meta http-equiv="refresh" content="0;url=http://somedomain.com" />

    <title></title>

  </head>

 <body></body>

</html>

Yet another way is :

<body onload="window.open(somepage)">

Another way is:

<script type="text/javascript">

    window.location = "somepage.html";

</script>

by (930 points)  
...