Javascript goto to url

Как в JS реализуется переход на другую страницу

В этой статье я расскажу, как в JS реализуется переход на другую страницу. А также приведу несколько простых примеров JavaScript редиректа .

Вы можете перенаправлять пользователя с одной веб-страницы на любую другую несколькими способами. В том числе с помощью обновления мета-данных HTML , перенаправления на стороне сервера. Например, используя файл .htaccess , PHP , и с помощью перенаправления на стороне клиента через JavaScript .

Но учтите, что неожиданные перенаправления, которые происходят в середине другого действия, раздражают посетителей. Поэтому использовать редирект нужно только, если это действительно необходимо и в том случае, если это будет иметь смысл с точки зрения пользователя.

Давайте рассмотрим, как можно использовать JavaScript для перенаправления пользователя на другую страницу.

Автоматическое JavaScript-перенаправление на другую страницу

Если нужно автоматически перенаправить пользователя с одной страницы ( URL1 ) на другую страницу ( URL2 ), можно использовать следующий код:

Читайте также:  Php проверка мобильного устройства

Необходимо вставить приведенный выше код на первую страницу ( URL1 ). Замените URL2 на нужный адрес страницы. Лучше поместить этот код внутри элемента ( а не в нижней части страницы ), чтобы страница перенаправлялась до того, как браузер начинает ее отображать.

СОВЕТ: Если вы используете встроенный JavaScript (т.е. без внешнего файла .js), не забудьте поместить код JavaScript в теги .

Перенаправление на другую страницу через X секунд

В этом примере мы будем осуществлять js редирект на другую страницу через некоторое время после загрузки страницы. Например, если нужно перенаправить посетителя на главную страницу после отображения страницы приветствия в течение 5 секунд:

setTimeout(function()< window.location.href = 'homepage-url'; >, 5 * 1000);

Необходимо вставить приведенный код JavaScript на странице приветствия. Не забудьте заменить homepage-url на URL-адрес домашней страницы.

Мы использовали метод setTimeout , чтобы указать скрипту выполнить перенаправление через 5 секунд ( умножаем 5 на 1000, чтобы преобразовать секунды в миллисекунды ).

СОВЕТ: В JavaScript значения времени всегда рассчитываются в миллисекундах.

Перенаправление на другую страницу, исходя из условия

Например, можно выполнить перенаправление в зависимости от браузера посетителя ( хотя это не рекомендуется ), размера экрана, времени суток, или другого условия.

Используйте следующий код для перенаправления посетителей, которые удовлетворяют определенному условию:

Например, этот код перенаправляет посетителей на другую страницу, если ширина их экрана меньше 600 пикселов:

Перенаправление на другую страницу на основе действий пользователя

Последний пример демонстрирует, как перенаправить посетителя, основываясь на его действиях. Вы можете привязать js редирект к любому типу действия пользователя. В данном примере для простоты мы будем обрабатывать нажатие кнопки.

Следующий код будет перенаправлять посетителя на целевую страницу после нажатия на #mybutton :

document.getElementById('mybutton').onclick = function() < window.location.href = 'redirect-url'; >;

Можно сделать то же самое, используя следующий код:

Также можно связать перенаправление с любым событием или действием пользователя. Только не забудьте удостовериться, что ваши редиректы не вызовут разочарования пользователей.

Я попытался рассмотреть все возможные случаи js редиректа на другую страницу . Если я когда-либо столкнусь с другими сценариями, я добавлю их в эту статью.

Источник

JavaScript go to URL | Navigate to a new URL example

Use the assign() or replace() methods to lets the user go to a new URL. You can replace the current URL value to go to another URL In JavaScript.

JavaScript go to URL Examples

Assigning a new value to window.location

To navigate to a new URL, use the location object from the Browser’s History API.

Complete code: will redirect us to a new URL

Using the window.assign() method

The assign method assigns the current URL with the assigned URL and adds it to the history stack.

window.location.assign('https://eyehunts.com');

Using the window.replace() method

Using the replace() method, you can navigate a user to a site and stop them from going back to the previous page.

window.location.replace('https://eyehunts.com');

Output: For all examples

JavaScript go to URL new URL example

Do comment if you have any doubts and suggestions on this JS URL topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Источник

Go to URL With Onclick in JavaScript

Go to URL With Onclick in JavaScript

  1. Go to URL Using window.open() in JavaScript
  2. Go to URL Using window.location in JavaScript

The window object is one of the most important objects used to talk to the browser. It represents the browser’s window. All the global variables, functions become members of the window object. Location object of the window is used to get the current page URL and also to change the URL for redirection.

In today’s article, we will learn how to go to URL with onclick in JavaScript.

The JavaScript window object provides two ways, the first is using the location attribute, and the second is using the open() method.

Go to URL Using window.open() in JavaScript

It is a Window interface method provided by JavaScript, which loads specified URL/resource into a new tab or existing browser with the specified name. This method will generate a new window for opening a specified URL. Every time window.open() method returns it contains about:blank . The actual URL will be loaded once the current script block completes its execution.

Syntax of window.open() in JavaScript

window.open(url, windowName, windowFeatures); 

Parameter

  • url : It is a mandatory parameter that accepts valid URLs, image paths, or other resources supported by browsers. If an empty string is passed, it will open a new tab with a blank URL.
  • windowName : It is an optional parameter, which specifies the name of the browsing context. This does not define the title of the window. Also, this window name should not contain any whitespace.
  • windowFeatures : It is an optional parameter. This parameter accepts comma-separated window properties of a new tab either in the form of name=value or just name if the property is boolean. Some of the features are the default position and size of the window object.
button type="button" id="btn" onclick="openGoogleByMethod()">Open Googlebutton> 
window.open("https://www.google.com"); 

Go to URL Using window.location in JavaScript

It is a read-only property of window.location , that returns the Location object. This object contains information on the current location of the document. Location object also contains other properties like href , protocol , host , hostname , port , etc.

Properties of window.location can also be accessed directly using location because the window object always remains at the top of the scope chain. Users can use the href property or assign the method of Location object to load/open other URL/resources.

Syntax

window.location = URL_PATH; window.location.href = URL_PATH; window.location.assign(URL_PATH); 

Parameter

  • URL_PATH : It is a mandatory parameter that accepts valid URL that needs to be opened. This URL can be an absolute URL, a relative URL, an anchor URL, or a new protocol.
button type="button" id="btn" onclick="openGoogle()">Open Googlebutton> 
window.location = "https://www.google.com"; window.location.href = "https://www.google.com"; 

Shraddha is a JavaScript nerd that utilises it for everything from experimenting to assisting individuals and businesses with day-to-day operations and business growth. She is a writer, chef, and computer programmer. As a senior MEAN/MERN stack developer and project manager with more than 4 years of experience in this sector, she now handles multiple projects. She has been producing technical writing for at least a year and a half. She enjoys coming up with fresh, innovative ideas.

Источник

JavaScript Redirect

Summary: in this tutorial, you will learn how to use JavaScript to redirect to a new URL or page.

Introduction to the JavaScript redirect

Sometimes, you want to redirect users from one page to another page that has a different URL.

For example, you can create an app landing page that purely redirects the users to the Google Play or Apple Store, depending on the operating system that their smartphones have.

  • Detect the operating system of the smartphones
  • Redirect to Apple Store if the OS is iOS and Google Play if the OS is Android.

The redirection can be done in the web browsers using JavaScript redirection API.

It’s important to note that JavaScript redirection runs entirely on web browsers. Therefore it doesn’t return the status code 301 (move permanently) like a server redirection.

Therefore, if you move the site to a separate domain or create a new URL for an old page, you should always use the server redirection.

Redirect to a new URL

To redirect web browsers to a new URL from the current page to a new one, you use the location object:

location.href = 'new_url';Code language: JavaScript (javascript)
location.href = 'https://www.javascripttutorial.net/';Code language: JavaScript (javascript)

Assigning a value to the href property of the location object has the same effect as calling the assign() method of the location object:

location.assign('https://www.javascripttutorial.net/');Code language: JavaScript (javascript)

Either of these calls will redirect to the new URL and create an entry in the history stack of the browser. It means that you can go back to the previous page via the Back button of the browser.

To redirect to a new URL without creating a new entry in the history stack of the browser, you use the replace() method of the location object:

location.replace('https://www.javascripttutorial.net/');Code language: JavaScript (javascript)

The following example creates a page that redirects web browsers to Google Play or Apple Store if the OS is Android or iOS. Otherwise, it’ll show a message indicating that the OS is not supported:

index.html

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript Redirect title> head> body> div class="message"> div> script src="js/app.js"> script> body> html>Code language: HTML, XML (xml)

js/app.js

const apps = < Android: 'https://play.google.com/', iOS: 'https://www.apple.com/store', >; const platform = () => < let userAgent = navigator.userAgent || navigator.vendor || window.opera; if (/windows phone/i.test(userAgent)) return 'Windows Phone'; if (/android/i.test(userAgent)) return 'Android'; if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) return 'iOS'; return null; >; const redirect = () => < let os = platform(); if (os in apps) < location.replace(apps[os]); >else < const message = document.querySelector('.message'); message.innerText = 'Your OS is not supported'; > >; redirect();Code language: JavaScript (javascript)

First, define an apps object with the keys are OS and values are URLs of the Google Play and Apple Store:

const apps = < Android: 'https://play.google.com/', iOS: 'https://www.apple.com/store', >;Code language: JavaScript (javascript)

Second, define a function that detects the OS:

const platform = () => < let userAgent = navigator.userAgent || navigator.vendor || window.opera; if (/windows phone/i.test(userAgent)) return 'Windows Phone'; if (/android/i.test(userAgent)) return 'Android'; if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) return 'iOS'; return null; >;Code language: JavaScript (javascript)

Third, create the redirect() function that detects the OS and redirects the web browser based on the detected OS:

const redirect = () => < let os = platform(); if (os in apps) < location.replace(apps[os]); >else < const message = document.querySelector('.message'); message.innerText = 'Your OS is not supported'; > >;Code language: JavaScript (javascript)

Finally, call the redirect() function:

Redirect to a relative URL

The following script redirects to the about.html which is on the same level as the current page.

location.href = 'about.html';Code language: JavaScript (javascript)

The following script redirects to contact.html page located in the root folder:

location.href = '/contact.html';Code language: JavaScript (javascript)

Redirect upon page loading

If you want to redirect to a new page upon loading, you use the following code:

window.onload = function( ) < location.href = "https://www.javascripttutorial.net/"; >Code language: JavaScript (javascript)

Summary

  • To redirect to a new URL or page, you assign the new URL to the location.href property or use the location.assign() method.
  • The location.replace() method does redirect to a new URL but does not create an entry in the history stack of the browser.

Источник

Оцените статью