Javascript window location error

Javascript window location error

Last updated: Dec 30, 2022
Reading time · 2 min

banner

# window.location.href is not a function Error in JavaScript

The «window.location.href is not a function» error occurs when we try to invoke the href property on the window.location object.

To solve the error, use the assign method on the window.location property.

window location href is not a function

Here is an example of how the error occurs.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> button id="btn">Change locationbutton> script src="index.js"> script> body> html>

And this is the code in our index.js file.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick() // ⛔️ TypeError: window.location.href is not a function window.location.href('https://google.com'); >);

We tried to invoke the href property as a function, so the error occurred.

Instead, you should use the window.location.assign method.

Copied!
const btn = document.getElementById('btn'); btn.addEventListener('click', function onClick() // ✅ works window.location.assign('https://google.com'); >);

The window.location.assign method enables us to navigate to a new page.

You could achieve the same result if you assign a string to the window.location.href property.

Copied!
btn.addEventListener('click', function onClick() // ✅ works window.location.href = 'https://google.com'; >);

If you load the page and click on the button, you will navigate to the webpage you assigned to the property.

If you need to check out all of the properties on the location object, here is a link from the MDN docs.

Similar methods to assign include:

  • window.location.reload() — reloads the current URL (like the refresh button).
  • window.location.replace() — redirects to the provided URL. The difference from the assign() method is that when using the replace() method, the current page is not saved in the session history, so users are not able to use the back button to navigate to it.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

Не работает window.location

При выборе элемента из списка отрабатывается alert, и идет переход на http://javascript.ru. При вводе текста и нажатии enter отрабатывается alert, перехода на другую страницу нет. Может кто подскажет почему и как это исправить. При использовании document.location.href ситуации аналогичная.

не работает window.location.href в chrome
Здравствуйте. Подскажите, пожалуйста, в чем проблема: в chrome не работает window.location.href.

не работает onClick=»window.location.href.
привет, в IE и Mozilla не работает функция onClick 🙁 .

Ошибка при редиректе (window.location.href)?
Здравствуйте! Есть код: var val = ‘<?php echo $sdf; ?>’; var ec = new flo(<>); getC(0); .

Переходы на сайте через window.location.href
Подскажите пожалуйста, делаю переходы на сайте через js window.location.href = "$_url"; .

Лучший ответ

Сообщение было отмечено Thisman как решение

Решение

form onsubmit="return false;">

Cмена window.location нормально работает, но нажатие энтер вызывает сабмит формы, что обновляет текущую страницу, если Вы в адрес посмотрите, то увидите что там гет параметры уехали.

Спасибо! У меня, конечно, было решение, но то, что Вы подсказали более правильно и красиво.

открыть 2 новые вкладки onclick=»window.location.href=
Всем привет. Не могу сделать, чтобы 2 новые вкладки открывались при нажатии на ссылку.. Вот код .

Функция $(location).attr(‘search’) не работает
Добрый день. У меня идёт такая ссылка. http://NHG Polyclinic/index.php?msg=0 Мне нужно получить.

Не работает window.close()
Не работает метод close() в Джавскрипте именно в браузерах Мозила и Гуглхром, что можно .

Не работает window.onload в javascript
ошибка Uncaught TypeError: Cannot read property ‘getContext’ of null <!DOCTTYPE html> <html>.

Источник

Читайте также:  Java android примеры приложений
Оцените статью