How to get a user’s location with javascript

Алан-э-Дейл       10.03.2024 г.

Получение координат

К сожалению, готовой функции для получения координат элемента относительно страницы нет. Но её можно легко написать самим.

Эти две системы координат жёстко связаны: .

Наша функция будет брать результат и прибавлять текущую прокрутку документа.

Результат : объект с координатами

Если нужно поддерживать более старые IE, то вот альтернативный, самый кросс-браузерный вариант:

Разберём что и зачем, по шагам:

  1. Получаем прямоугольник.
  2. Считаем прокрутку страницы. Все браузеры, кроме IE8- поддерживают свойство . В более старых IE, когда установлен DOCTYPE, прокрутку можно получить из , ну и наконец если DOCTYPE некорректен – использовать .
  3. В IE документ может быть смещён относительно левого верхнего угла. Получим это смещение.
  4. Добавим прокрутку к координатам окна и вычтем смещение , чтобы получить координаты нужного нам элемента.

Есть альтернативный способ нахождения координат – это пройти всю цепочку от элемента вверх и сложить отступы .

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

Вот функция, реализующая такой подход.

Казалось бы, код нормальный. И он как-то работает, но разные браузеры преподносят «сюрпризы», включая или выключая размер рамок и прокруток из , некорректно учитывая позиционирование. В итоге результат не всегда верен. Можно, конечно, разобрать эти проблемы и посчитать действительно аккуратно и правильно этим способом, но зачем? Ведь есть .

Вы можете увидеть разницу между вычислением координат через и на примере.

В прямоугольнике ниже есть 3 вложенных . Все они имеют , кое-кто из них имеет .

Кликните по внутреннему (жёлтому) элементу, чтобы увидеть результаты обоих методов: и , а также реальные координаты курсора – (мы обсудим их позже в статье Мышь: IE8-, исправление события).

Кликните, чтобы получить координаты getOffsetSum и getCoords

getOffsetSum:значение getOffsetSum()

getCoords:значение getCoords()

mouse:координаты мыши

При клике на любом месте жёлтого блока вы легко увидите разницу между и .

Для того, чтобы узнать, какой же результат верный, кликните в левом-верхнем углу жёлтого блока, причём обратите внимание – кликать нужно не на жёлтом, а на чёрном, это рамка, она тоже входит в элемент. Будут видны точные координаты мыши, так что вы можете сравнить их с. Пример клика в правильном месте (обратите внимание на разницу координат):

Пример клика в правильном месте (обратите внимание на разницу координат):

Именно всегда возвращает верное значение.

The getCurrentPosition() Method — Return Data

The method returns an object on success. The latitude,
longitude and accuracy properties are always returned. The other properties are returned
if available
:

Property Returns
coords.latitude The latitude as a decimal number (always returned)
coords.longitude The longitude as a decimal number (always returned)
coords.accuracy The accuracy of position (always returned)
coords.altitude The altitude in meters above the mean sea level (returned if available)
coords.altitudeAccuracy The altitude accuracy of position (returned if available)
coords.heading The heading as degrees clockwise from North (returned if available)
coords.speed The speed in meters per second (returned if available)
timestamp The date/time of the response (returned if available)

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

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

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

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

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

Переадресация JavaScript: перенаправление при загрузке

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

Просто замените URL-адрес из примера на тот адрес, куда вы хотите перенаправлять. Следует отметить, что при этом виде переадресации, посетители вообще не увидят вашу веб-страницу и будут моментально перенаправлены на целевой адрес.

Переадресация JavaScript: перенаправление после определенного периода времени

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

Функция JavaScript location href , приведенная выше, перенаправит пользователя со страницы через 3 секунды после полной загрузки. Вы можете изменить значение 3000 ( 3 x 1000 в миллисекундах ) на свое усмотрение.

Переадресация 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 Redirect: How to Redirect a Web Page with JavaScript»

Элементы документа как свойства окна

Если для именования элемента в HTML-документе используется атрибут id и если объект Window еще не имеет свойства, имя которого совпадает со значением этого атрибута, объект Window получает неперечислимое свойство с именем, соответствующим значению атрибута id, значением которого становится объект HTMLElement, представляющий этот элемент документа.

Как вы уже знаете, объект Window играет роль глобального объекта, находящегося на вершине цепочки областей видимости в клиентском JavaScript. Таким образом, вышесказанное означает, что атрибуты id в HTML-документах становятся глобальными переменными, доступными сценариям. Если, например, документ включает элемент <button id=»ok»/>, на него можно сослаться с помощью глобальной переменной ok.

Однако важно отметить, что этого не происходит, если объект Window уже имеет свойство с таким именем. Элементы с атрибутами id, имеющими значение «history», «location» или «navigator», например, не будут доступны через глобальные переменные, потому что эти имена уже используются

Аналогично, если HTML-документ включает элемент с атрибутом id, имеющим значение «x» и в сценарии объявляется и используется глобальная переменная x, явно объявленная переменная скроет неявную переменную, ссылающуюся на элемент.

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

Неявное использование идентификаторов элементов в качестве глобальных переменных — это пережиток истории развития веб-браузеров. Эта особенность необходима для сохранения обратной совместимости с существующими веб-страницами, но использовать ее сейчас не рекомендуется — в любой момент производители браузеров могут определить новое свойство в объекте Window, что нарушит работу любого программного кода, использующего неявно определяемое свойство с этим именем. Поиск элементов лучше выполнять явно, с помощью метода document.getElementById().

Get Current URL in React — Vanilla JavaScript Solution

Since React is based on regular JavaScript, you can access the property on the interface. To get the full path of the current URL, you can use , and to get the path without the root domain, access instead.

Let’s look at the example:

If you render the component on playcode.io, the console will show the full URL to your project. In this case, that would be . If you instead, the console output will be . Follow this link to play around with the code yourself.

Reading is a good, simple solution to get the current URL. However, it relies on the general interface.

If you’re looking for a React-specific solution, continue reading.

JavaScript Window location Methods/Functions

  • window.location.href => get the current webpage.
  • window.location.hostname => get the webhost (domain name).
  • window.location.pathname => get filename path of the current webpage.
  • window.location.protocol => get the web protocol used (http: or https:)
  • window.location.assign => loads a new document.

1: The Window location href

The window.location.href method return the current webpage URL.

var exp = window.location.href;

document.write("Current url of browser =  "+exp);

2: Window Location Hostname

The window.location.hostname method used to which is return the name of the current pages internet host.

var exp = window.location.hostname;

document.write("hostname =  "+exp);

3: Window Location Pathname

The window.location.pathname method is used for get the pathname of the current webpage.

var exp = window.location.pathname;

document.write("Pathname =  "+exp);

4: Window Location Protocol

The window.location.protocol method is used for get the protocol of the current webpage.

var exp = window.location.protocol;

document.write("Protocol =  "+exp);

Get Current URL via React Router

React provides a package, and separated object via . It is essentially the same object available on the interface, but it is customized for React.

This object represents the app’s current URL. The easiest way to access it is by reading the object of the .

However, to provide via props, you must install , and the child component must be connected to the component. For example:

In this example, the App component will have access to the object via props. Inside this component, we can read , which will return a path URL that doesn’t include the root domain.

Child components rendered with a component also have the access to prop. Here’s an example:

In this case, the App component will still retain access to the prop.

If returns , your React component is most likely rendered outside the custom component. In this case, you can import high-order component (HOC) and use it to access and props.

can be imported from the package. Here’s an example:

Wrapping the default export component in a HOC will allow you to access that would be otherwise only available for components rendered with a special component.

Открытие и закрытие окон

Открыть новое окно веб-браузера (или вкладку, что обычно зависит от настроек браузера) можно с помощью метода open() объекта Window. Метод Window.open() загружает документ по указанному URL-адресу в новое или в существующее окно и возвращает объект Window, представляющий это окно. Он принимает четыре необязательных аргумента:

Первый аргумент open() — это URL-адрес документа, отображаемого в новом окне. Если этот аргумент отсутствует (либо является пустой строкой), будет открыт специальный URL пустой страницы about:blank.

Второй аргумент open() — это строка с именем окна. Если окно с указанным именем уже существует (и сценарию разрешено просматривать содержимое этого окна), используется это существующее окно. Иначе создается новое окно и ему присваивается указанное имя. Если этот аргумент опущен, будет использовано специальное имя «_blank», т.е

будет открыто новое неименованное окно.
Обратите внимание, что сценарии не могут просто так указывать имена окон и не могут получать контроль над окнами, используемыми другими веб-приложениями: они могут указывать имена только тех существующих окон, которыми им «разрешено управлять» (термин взят из спецификации HTML5). Проще говоря, сценарий может указать имя существующего окна, только если это окно содержит документ, происходящий из того же источника, или если это окно было открыто самим сценарием (или рекурсивно открытым окном, которое открыло это окно).
Кроме того, если одно окно является фреймом, вложенным в другое окно, сценарии в любом из них получают возможность управлять другим окном

В этом случае можно использовать зарезервированные имена «_top» (для обозначения вмещающего окна верхнего уровня) и «_parent» (для обозначения ближайшего вмещающего окна).

Третий необязательный аргумент open() — это список параметров, определяющих размер и видимые элементы графического пользовательского интерфейса нового окна. Если опустить этот аргумент, окно получает размер по умолчанию и полный набор графических элементов: строку меню, строку состояния, панель инструментов и т.д. В браузерах, поддерживающих вкладки, это обычно приводит к созданию новой вкладки. Этот третий аргумент является нестандартным, и спецификация HTML5 требует, чтобы браузеры игнорировали его.
Указывать четвертый аргумент open() имеет смысл, только если второй аргумент определяет имя существующего окна. Этот аргумент — логическое значение, определяющее, должен ли URL-адрес, указанный в первом аргументе, заменить текущую запись в истории просмотра окна (true) или требуется создать новую запись (false). Если этот аргумент опущен, используется значение по умолчанию false.

Значение, возвращаемое методом open(), является объектом Window, представляющим вновь созданное окно. Этот объект позволяет сослаться в JavaScript-коде на новое окно так же, как исходный объект Window ссылается на окно, в котором выполняется сценарий:

В окнах, созданных методом window.open(), свойство opener ссылается на объект Window сценария, открывшего его. В других случаях свойство opener получает значение null:

Метод Window.open() часто используется рекламодателями для создания «всплывающих окон» с рекламой, когда пользователь путешествует по Всемирной паутине. Такие всплывающие окна могут раздражать пользователя, поэтому большинство веб-браузеров реализуют механизм блокирования всплывающих окон. Обычно вызов метода open() преуспевает, только если он производится в ответ на действия пользователя, такие как щелчок мышью на кнопке или на ссылке. Попытка открыть всплывающее окно, которая производится, когда браузер просто загружает (или выгружает) страницу, как в приведенном примере, обычно оканчивается неудачей.

Новое окно открывается при помощи метода open() и закрывается при помощи метода close(). Если объект Window был создан сценарием, то этот же сценарий сможет закрыть его следующей инструкцией:

Get Current URL React Router Hooks

Functional components allow you to use hooks. In our situation, is an excellent hook that provides an easy way to access the object.

It can be imported from the package. This example uses the hook to get a object and store it in a variable.

Let’s have a look:

Once you’ve stored the object in a variable, you can access the path (URL without the root domain) by accessing .

You can also access the property of the object.

The hook allows you to get access to it. However, due to mutability concerns, official docs recommend sticking with the object.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Use JavaScript to Refresh a Page

There are times when you will want to programatically refresh or reload a page using JavaScript. Typically you would place a button or action element on the page for the user to initiate the refresh. Automatically performing a page refresh can be a confusing and jarring experience for your user, so minimize that tactic.

The location.reload method reloads the current document, just like the user pressed F5 or the browser reload button.

The default setting reloads the page from browser cache, if it is available. You can force the method to bypass local cache and retrieve the document from the network by passing true to the method.

I think the best etiquette is to use JavaScript to refresh the page in response to a user action. This is typically in response to a click or touch event handler. I also think in this scenario you are also intending to retrieve from the network, so you will also want to force this action.

Here is an over simplified example:

You should be aware, if the user has scroll the page the browser may not retain their current scroll position. Most modern browsers seem to handle this well, but this is not always the case.

You are refreshing a page, and the content and document structure has most likely changed from what their originally rendered. In these cases the browser may not be able to determine where to reliably place the scroll position. In these cases the browser does not scroll the page and the positioning is the top.

There is also a security check in place with this call to prevent external scripts from using this method maliciously. This relates to the Same origin Policy. If this happens a DOMException is thrown with a SECURITY_ERROR.

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()
cos()
cosh()
E
exp()
floor()
LN2
LN10
log()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
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.

Таймеры

Функции setTimeout() и setInterval() позволяют зарегистрировать функцию, которая будет вызываться один или более раз через определенные интервалы времени. Это очень важные функции для клиентского JavaScript, и поэтому они были определены как методы объекта Window, несмотря на то что являются универсальными функциями, не выполняющими никаких действий с окном.

Метод setTimeout() объекта Window планирует запуск функции через определенное число миллисекунд. Метод setTimeout() возвращает значение, которое может быть передано методу clearTimeout(), чтобы отменить запланированный ранее запуск функции.

Метод setInterval() похож на setTimeout(), за исключением того, что он автоматически заново планирует повторное выполнение через указанное количество миллисекунд:

Подобно setTimeout(), метод setInterval() возвращает значение, которое может быть передано методу clearInterval(), чтобы отменить запланированный запуск функции.

В следующем примере определяется вспомогательная функция, которая ожидает указанный интервал времени, многократно вызывает указанную функцию и затем отменяет запланированные вызовы по истечении другого заданного интервала времени. Этот пример демонстрирует использование методов setTimeout(), setInterval() и clearInterval():

По исторически сложившимся причинам в первом аргументе методам setTimeout() и setInterval() допускается передавать строку. В этом случае строка будет интерпретироваться (как с применением функции eval()) через указанный интервал времени. Спецификация HTML5 (и все браузеры, кроме IE) допускает передавать методам setTimeout() и setInterval() дополнительные аргументы после первых двух. Все эти дополнительные аргументы будут передаваться функции, вызов которой планируется этими методами. Однако если требуется сохранить совместимость с IE, эту возможность использовать не следует.

Если методу setTimeout() указать величину интервала 0 миллисекунд, указанная функция будет вызвана не сразу, а «как только такая возможность появится», т.е. как только завершат работу все обработчики событий.

Redirect to a New Address

When you have changed an address, for example a new domain name, you should perform a 301 redirect. This is where the server sends an HTTP status code of 301, with the new address.

A 301 status code tells the user agent: i.e. the browser or search engine spider, there is a new address. This is sort of like when you move and submit an address change to the post office. Your mail is forwarded.

A 301 redirect allows you to keep the traffic and hopefully your search engine ranking.

Normally you would do this from the server. There are times when this is not possible and you would need to use a JavaScript redirect to a URL.

This is pretty simple, just include one of the following snippets:

I would recommend using replace because the original URL is not valid. So retaining it in their session history might confuse them and trigger an automatic redirect anyway.

location.replace is useful for any 301 redirect scenario, including when you need to redirect from HTTP to HTTPS. But a more succinct way to redirect from HTTP to HTTPS using JavaScript is the following code snippet:

I do recommend configuring your server to send the proper HTTP redirection headers because they are much more efficient. This applies to both new addresses and HTTP to HTTPS.

# Location Object

The returns a object. Which gives you information about the current location of the page. But you can also access the object in several ways.

The reason we can do this is because these are global variables in our browser.

window.location vs location

All 4 of these properties point at the same object. I personally prefer and would actually avoid using . Mainly because reads more like a generic term and someone might accidentally name their variable that, which would override the global variable. Take for example:

I think that most developer is aware that is a global variable. So you’re less likely to cause confusion. To be honest, I had no idea was a global variable until I wrote this post . So my recommendation is to be more explicit and use instead

Here’s my personal order of preference:

Of course, this is just my preference. You’re the expert of your codebase, there is no best way, the best way is always the one that works best for you and your team

Redirect Using JavaScript

Ideally, a redirect should be issued from the backend with correct HTTP redirect headers sent to the client. But if we must redirect from JavaScript, we can do so using the methods below:

// redirect to a new page
window.location.href = 'https://www.example.com/';

// same as window.location.href = ...
window.location = 'https://www.example.com/';
window.location.assign('https://www.example.com/');

// redirect to new page and,
// replace the original document in browser history with new one
window.location.replace('https://www.example.com/');

In most cases, the function might be the best option as it won’t cause redirect loops when users hit the browser’s back button.

Some browsers and most web crawlers may not execute JavaScript for various reasons, which is why having a fallback in place is a good idea.

Fallback When/If JavaScript Is Disabled:

Preferably, we should issue HTTP headers originating from the backend (server-side) to issue a redirect with appropriate redirection code. However, since we’re specifically talking about JavaScript / Frontend redirection, we could use HTML’s meta tag refresh (in the section of the web page) to instruct the browser to refresh the current web page (or an ) after a specified time interval (in seconds). Consider the following example:

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

The specified in the attribute instructs the browser to redirect immediately. Changing it to a positive non-zero value would instruct the browser to wait before refreshing the page (the value is interpreted in seconds).

Additionally, we can place a fallback, for example a link, for older browsers in case the refresh doesn’t work:

<p>
    <a href="https://example.com/">Redirect</a>
</p>

To make sure, the code only executes when/if the browser has JavaScript disabled, we could wrap the tag (or other relevant code) inside a tag like so:

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

Potential Side-Effects:

  • If a page redirects too quickly (i.e. in less than 2-3 seconds), it can break the Back button on the browser as each time you move back to the redirecting page, redirection will occur again almost immediately. This is especially bad in terms of usability as it can trap the user on the page he was redirected to.
  • It can be considered as a «Doorway Page» which is considered as an un-ethical SEO process by search engines.
  • Sometimes a mistake, or poorly planned redirections, can cause an infinite sequence of redirects, redirecting back and forth between two or more pages.

JavaScript Redirect’s Impact on SEO:

Why a JavaScript Redirect May Impact Your Search Engine Ranking Negatively:

Like mentioned previously, most web crawlers may not execute JavaScript which may negatively impact your web page’s search engine ranking. You might imagine using refresh would resolve the issue for all web crawlers, but such is not the case. In fact, an HTML page that contains a refresh element returns an HTTP status code of (which is different from redirect status codes such as 301, 302, etc.). How that HTML response (with a refresh tag) is processed and/or interpreted by a user-agent/bot/crawler depends entirely on the agent, its specific purpose and its programming.

Alternatives to JavaScript Redirect, Without Compromising SEO:

The best way to overcome these issues may be:

  1. To add a in the section of your web page to inform search engines of a duplicate page (e.g. ); this is easier to implement as it doesn’t involve doing anything on the server-side. However, you must keep in mind that all search engines or web crawlers may not honor it;
  2. To issue either of the following HTTP headers from the web server (or a backend/server-side script):
    1. To properly issue an HTTP redirect header with most-appropriate such as , , etc., or;
    2. To display a for web pages that you may want to kill off and let die.

Although a may be considered bad for SEO in most cases, it may still be more meaningful in some. To help determine what course of action may be best suited in your particular case, you might want to ask yourself the following:

  1. Does the page receive important links to it from external sources?
  2. Does the page receive a considerable amount of visitor traffic?
  3. Is it an obvious (or a popular) URL that visitors/links intended to reach?

If answer to any of those is a yes, you might want to consider a 3xx redirect instead of a . Otherwise, it may be alright to issue a – the reason being 1) we’d save up bandwidth from search engines trying to crawl and index a junk/stale page, and 2) we’d be able to inform the user about the error and display a search option and/or other relevant links instead (which may enhance the user experience).

Попытка 1. Суммируем offset’ы

Логика этого подхода довольно проста.

Она заключается в том, что браузер позиционирует элементы относительно друг друга, и у каждого элемента есть свой «родитель по позиционированию»: .

В качестве обычно выступает родитель . Но это не всегда так.

Например, для элемента с родителем по позиционированию является ближайший позиционированный родитель, то есть первый элемент в цепочке вложенности, у которого свойство — одно из: , или (не поддерживается IE.

Наиболее подробно это описано в стандарте CSS: . Этот самый «containing block» — как раз и определяет , от которого отсчитывается позиция элемента.

Как браузер находит

Двигаемся вверх по цепочке родителей , останавливаясь на следующих элементах, которые являются :

  • элемент, у которого — не (значение по умолчанию)
  • элементы table,th,td — если

У элемента никогда нет .

В IE 7+/Opera у элементов с нет .

Сдвиг относительно ‘а задается свойствами :

Остается пройтись по всем и просуммировать сдвиги. Последним обычно является :

function getOffsetSum(elem) {
    var top=0, left=0
    while(elem) {
        top = top + parseFloat(elem.offsetTop)
        left = left + parseFloat(elem.offsetLeft)
        elem = elem.offsetParent        
    }
    
    return {top: Math.round(top), left: Math.round(left)}
}

Основных проблем с этим кодом две.

  1. Он слегка глючит, в разных браузерах — по-разному. Есть проблемы с border’ами элементов, ошибки при прокрутке внутри элементов и некоторые другие.
  2. Он медленный. Каждый раз приходится пройти всю цепочку ‘ов.

Вместо того, чтобы писать длинный кроссбраузерный код с разбором багов, который уж точно везде работает корректно, рассмотрим альтернативное решение, которое мало того что соответствует стандарту — его отлично поддерживают Internet Explorer 6+, Firefox 3+ и Opera 9.62+.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.