Location

Методы переадресации JavaScript

В JavaScript window location или объект location используется, чтобы получить информацию о местоположении текущей веб-страницы (документа), а также для его изменения. Ниже приведен список способов, которые могут быть использованы для реализации переадресации JavaScript:

//Устанавливает новое местоположение текущего окна.
window.location = "http://www.example.com";
//Устанавливает новую гиперссылку (URL) для текущего окна.
window.location.href = "http://www.example.com";
// Присваивает новый URL текущему окну. 
window.location.assign("http://www.example.com");
//Заменяет положение текущего окна на новое. 
window.location.replace("http://www.example.com");
//Задает местоположение самого текущего окна. 
self.location = "http://www.example.com";
// Задает положение самого верхнего окна относительно текущего.
top.location = "http://www.example.com";

Хотя приведенные выше строки JavaScript кода выполняют схожую работу, у них есть небольшие отличия. Например, если вы используете перенаправление top.location внутри элемента iframe, то это принудительно перенаправит на главное окно. Еще один момент, о котором стоит помнить: location.replace() заменяет текущий документ, удаляя его из истории и делая его недоступным с помощью кнопки «Назад» в браузере.

Для реализации кроссбраузерности мы рекомендуем использовать следующий код JavaScript windows location:

window.location.href = "http://www.example.com";

Также вы можете зайти на эту страницу, чтобы подробнее узнать, как работает window.location.

Переадресация JavaScript: перенаправление со страницы после события или действия пользователя

Иногда нужно отправить пользователя на другую страницу после определенного события или совершенного действия. В таких случаях можно использовать проверку условия или закрепить за элементом событие для выполнения переадресации. Рассмотрим два следующих примера:

<script>
// Проверяем, верно ли условие, и затем перенаправляем. 
if ( ... ) {
  window.location.href = "http://www.example.com";
}
</script>

Приведенный выше код JavaScript document location href выполнит перенаправление, если условие верно:

<script>
// событие onclick присвоено элементу #button.
document.getElementById("button").onclick = function() {
  window.location.href = "http://www.example.com";
};
</script>

Приведенный выше код выполнит перенаправление, когда пользователь нажмет на элемент #button.

Так работает переадресация в JavaScript. Надеемся, эти примеры помогут вам в организации переадресации веб-страниц.

Пожалуйста, оставляйте ваши комментарии по текущей теме материала. За комментарии, отклики, дизлайки, лайки, подписки огромное вам спасибо!

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Window Object Methods

Method Description
alert() Displays an alert box with a message and an OK button
atob() Decodes a base-64 encoded string
blur() Removes focus from the current window
btoa() Encodes a string in base-64
clearInterval() Clears a timer set with setInterval()
clearTimeout() Clears a timer set with setTimeout()
close() Closes the current window
confirm() Displays a dialog box with a message and an OK and a Cancel button
focus() Sets focus to the current window
getComputedStyle() Gets the current computed CSS styles applied to an element
getSelection() Returns a Selection object representing the range of text selected by the user
matchMedia() Returns a MediaQueryList object representing the specified CSS media query string
moveBy() Moves a window relative to its current position
moveTo() Moves a window to the specified position
open() Opens a new browser window
print() Prints the content of the current window
prompt() Displays a dialog box that prompts the visitor for input
requestAnimationFrame() Requests the browser to call a function to update an animation before
the next repaint
resizeBy() Resizes the window by the specified pixels
resizeTo() Resizes the window to the specified width and height
scroll() Deprecated. This method has been replaced by the scrollTo() method.
scrollBy() Scrolls the document by the specified number of pixels
scrollTo() Scrolls the document to the specified coordinates
setInterval() Calls a function or evaluates an expression at specified intervals (in milliseconds)
setTimeout() Calls a function or evaluates an expression after a specified number of milliseconds
stop() Stops the window from loading

❮ Previous
Next ❯

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Window Object Properties

Property Description
closed Returns a Boolean value indicating whether a window has been closed or not
console Returns a reference to the Console object, which provides methods for logging information to the browser’s console (See Console object)
defaultStatus Sets or returns the default text in the statusbar of a window
document Returns the Document object for the window (See Document object)
frameElement Returns the <iframe> element in which the current window is inserted
frames Returns all <iframe> elements in the current window
history Returns the History object for the window (See History object)
innerHeight Returns the height of the window’s content area (viewport) including
scrollbars
innerWidth Returns the width of a window’s content area (viewport) including
scrollbars
length Returns the number of <iframe> elements in the current window
localStorage Allows to save key/value pairs in a web browser. Stores the data with no expiration date
location Returns the Location object for the window (See Location object)
name Sets or returns the name of a window
navigator Returns the Navigator object for the window (See Navigator object)
opener Returns a reference to the window that created the window
outerHeight Returns the height of the browser window, including toolbars/scrollbars
outerWidth Returns the width of the browser window, including toolbars/scrollbars
pageXOffset Returns the pixels the current document has been scrolled (horizontally) from the upper left corner of the window
pageYOffset Returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window
parent Returns the parent window of the current window
screen Returns the Screen object for the window (See Screen object)
screenLeft Returns the horizontal coordinate of the window relative to the screen
screenTop Returns the vertical coordinate of the window relative to the screen
screenX Returns the horizontal coordinate of the window relative to the screen
screenY Returns the vertical coordinate of the window relative to the screen
sessionStorage Allows to save key/value pairs in a web browser. Stores the data for one
session
scrollX An alias of pageXOffset
scrollY An alias of pageYOffset
self Returns the current window
status Sets or returns the text in the statusbar of a window
top Returns the topmost browser window

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
constructor
compile()
exec()
g
global
i
ignoreCase
lastIndex
m
multiline
n+
n*
n?
n{X}
n{X,Y}
n{X,}
n$
^n
?=n
?!n
source
test()
toString()

(x|y)
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx

JS Statements
break
class
continue
debugger
do…while
for
for…in
for…of
function
if…else
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

JavaScript Redirect Methods

You can redirect a web page via JavaScript using a number of methods. We will quickly list them and conclude with the recommended one.

In JavaScript, window.location or simply location object is used to get information about the location of the current web page (document) and also to modify it. The following is a list of possible ways that can be used as a JavaScript redirect:

// Sets the new location of the current window.
window.location = "https://www.example.com";

// Sets the new href (URL) for the current window.
window.location.href = "https://www.example.com";

// Assigns a new URL to the current window.
window.location.assign("https://www.example.com");

// Replaces the location of the current window with the new one.
window.location.replace("https://www.example.com");

// Sets the location of the current window itself.
self.location = "https://www.example.com";

// Sets the location of the topmost window of the current window.
top.location = "https://www.example.com";

Though the above lines of JS code accomplish a similar job in terms of redirection, they have slight differences in their usage. For example, if you use top.location redirect within an iframe, it will force the main window to be redirected. Another point to keep in mind is that location.replace() replaces the current document by moving it from the history, hence making it unavailable via the Back button of the browser.

It is better to know your alternatives but if you want a cross-browser compliant JavaScript redirect script, our recommendation will be to use the following in your projects:

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

Simply insert your target URL that you want to redirect to in the above code. You can also check this page to read more about how window.location works. Now, let’s continue with our examples.

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

Sometimes, you may want to send the user to another page after a certain event or action takes place, such as a button click, an option selection, a layout change, a form submission, a file upload, an image drag, a countdown timer expiration or things like that. In such cases, you can either use a condition check or assign an event to an element for performing the redirect. You can use the following two examples to give you a basic idea:

<script>
// Check if the condition is true and then redirect.
if ( ... ) {
  window.location.href = "https://www.example.com";
}
</script>

The above code will do the redirection if the condition is true.

<script>
// onclick event is assigned to the #button element.
document.getElementById("button").onclick = function() {
  window.location.href = "https://www.example.com";
};
</script>

The above code will do the redirection when the user clicks the #button element.

This is how JavaScript redirect basically works. We hope that the above examples will help you while handling your web page redirects.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector