- Шпаргалка по window.location
- Saved searches
- Use saved searches to filter your results more quickly
- Window.location.href is undefined on react-native #3790
- Window.location.href is undefined on react-native #3790
- Comments
- Bug report
- Describe the bug
- To Reproduce
- Expected behavior
- Screenshots
- System information
- Window location.href
- Syntax
- Property Value
- Return Value
- More Examples
- Browser Support
- COLOR PICKER
- Report Error
- Thank You For Helping Us!
- Javascript location href undefined
- # window.location.href is not a function Error in JavaScript
- # Additional Resources
Шпаргалка по window.location
https://voiti-v-it.com/posts/76?filter=JS#2 window.location.origin → ‘https://voiti-v-it.com’ .protocol → ‘https:’ .host → ‘voiti-v-it.com’ .hostname → ‘voiti-v-it.com’ .port → » .pathname → ‘posts/76’ .search → ‘?filter=JS’ .hash → ‘#2’ .href → ‘https://voiti-v-it.com/posts/76?filter=JS#2’ window.location.assign(‘url’) .replace(‘url’) .reload() .toString()
window.location .origin Базовый URL (Протокол + имя хоста + номер порта) .protocol Протокол (http: или https) .host Доменное имя + порт .hostname Доменное имя .port Имя порта .pathname Строка пути (относительно хоста) .search Часть строки, которая следует после? (включая ?) .hash Часть строки, которая следует после # (якорь или идентификатор фрагмента) .href Полный URL
В моем примере выше ты заметишь, что
возвращают одно и то же значение. Так в чем же разница. Ну, это связано с номером порта. Давай взглянем.
https://voiti-v-it.com window.location.host; // ‘voiti-v-it.com’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // »
http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’
будет содержать номер порта, тогда как
будет возвращать только имя хоста.
Ты можешь не только вызвать свойства объекта
чтобы получить информацию об URL. Ты можешь использовать его для установки новых свойств и изменения URL. Посмотрим, что я имею в виду.
http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’
Вот полный список свойств, которые ты можешь изменить:
http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’
Единственное свойство, которое ты не можешь установить, это
Это свойство доступно только для чтения.
который дает тебе информацию о текущем местоположении страницы. Ты также можешь получить доступ к объекту Location несколькими способами.
http://voiti-v-it.com:8080 window.location.host; // ‘voiti-v-it.com:8080’ window.location.hostname; // ‘voiti-v-it.com’ window.location.port; // ‘8080’
Объект доступен таким образом, потому что является глобальной переменной в браузере.
Каждый из 4х свойств выше указывают на один и тот же объект
и на самом деле не буду использовать
Главным образом потому, что
читается больше как общий термин, и кто-то может случайно назвать свою переменную, которая переопределяет глобальную переменную. Взять, к примеру:
Я думаю, что большинство разработчиков знают, что
является глобальной переменной. Так что у тебя меньше шансов вызвать путаницу. Поэтому я рекомендую использовать
Вот мой личный порядок предпочтений:
// ✅ 1. window.location // 🏆 2. document.location // ❌ 3. window.document.location // почему бы просто не использовать #1 or #2 😅 4. location // чувствуется слишком двусмысленно 😵
Конечно, это всего лишь мои предпочтения. Ты эксперт в своей кодовой базе, лучшего способа нет, лучший всегда тот, который подходит тебе и твоей команде.🤓
window.location .assign() Навигация происходит по указанному URL .replace() Навигация происходит по указанному URL & и текущая страница удаляется из истории .reload() Перезагружает текущую страницу .toString() Returns the URL
window.location.toString
Этот метод возвращает USVString URL. Версия только для чтения
Другими словами, ты можешь использовать его для получения значения
// https://voiti-v-it.com window.location.href; // https://voiti-v-it.com window.location.toString(); // https://voiti-v-it.com
Что касается использования, я не смог найти много информации о том, что лучше; но если ты это сделаешь, пожалуйста, поделись в комментах 😊. Я нашел тест производительности на разницу.
Один момент, который я хочу отметить в отношении этих тестов скорости, заключается в том, что они зависят от браузера. Различные браузеры и версии будут иметь разные результаты. Я использую Chrome, поэтому href вышел быстрее остальных. Так что я буду этим пользоваться. Также я думаю, что он читается более явно, чем
предоставит URL, тогда как
выглядит как нечто, преобразуемое в строку.😅
Оба эти метода помогут тебе перейти по другому URL. Разница в том, что
сохранит твою текущую страницу в истории, поэтому твой пользователь может использовать кнопку «назад» для перехода к ней. Принимая во внимание метод
он не сохраняет его истории. Это немного смущает, да? Меня тоже. Давай пройдемся по примерам.
1. Открыть новую вкладку 2. Перейти https://voiti-v-it.com (текущая страница) 3. Загрузить нвоую страницу 👉 `window.location.assign(‘https://www.w3schools.com’)` 4. Нажать «назад» 5. Вернемся на 👉 https://voiti-v-it.com
1. Открыть новую вкладку 2. Перейти https://voiti-v-it.com (текущая страница) 3. Загрузить нвоую страницу 👉 `window.location.assign(‘https://www.w3schools.com’)` 4. Нажать «назад» 5. Вернемся на 👉 чистую страницу
Мне просто нужно подчеркнуть «текущая страница» в определении. Это страница прямо перед
1. Открыть новую вкладку 2. Перейти www.developer.mozilla.org 3. Перейти https://voiti-v-it.com 👈 это будет текущая страница 4. window.location.assign(‘https://www.w3schools.com’); // Перейдет к #3 4. window.location.replace(‘https://www.w3schools.com’); // Перейдет к #2
Теперь ты знаешь, что мы можем изменить свойства
присвоив значение с помощью
Точно так же существуют методы, к которым мы можем получить доступ для выполнения некоторых действий. Итак, что касается «как перенаправить/редиректить на другую страницу», то есть 3 способа.
// Установить свойство href window.location.href = ‘https://voiti-v-it.com’; // Использование Assign window.location.assign(‘https://voiti-v-it.com’); // Использование Replace window.location.replace(‘https://voiti-v-it.com’);
replace vs assign vs href
Все три перенаправляют, разница связана с историей браузера.
здесь одинаковы. Они сохранят твою текущую страницу в истории, а
— нет. Так что, если ты предпочитаешь опыт создания, когда навигация не может вернуться на исходную страницу, используй
Таким образом, вопрос сейчас:
Я считаю, что это личные предпочтения. Мне больше нравится
потому что это метод, поэтому мне кажется, что я выполняю какое-то действие. Также есть дополнительный бонус в том, что его проще тестировать. Я писал много Jest-тестов, поэтому, используя метод можно просто замокать данные.
window.location.assign = jest.fn(); myUrlUpdateFunction(); expect(window.location.assign).toBeCalledWith(‘http://my.url’);
Но для тех, которые болеют за
для редиректа страницы. Я нашел тест производительности и он работает в моей версии Chrome быстрее. Опять же, тесты производительности варьируются в зависимости от браузера и разных версий, сейчас это может быть быстрее, но, возможно, в будущих браузерах всё может измениться.
Как это все появилось 👍
Ладно, я готов с вами поделиться как появилась эта шпаргалка. Я гуглил, как редиректить на другую страницу, и столкнулся с объектом
Иногда я чувствую, что разработчик является журналистом или детективом — для того, чтобы собрать всю доступную информацию, приходится много копаться и прочесывать разные источники. Честно говоря, я был ошеломлен материалами, они все были “о разном”, а я просто хотел всё из одного источника. Я не мог найти много полной информации, поэтому я подумал, а расскажу-ка я об этом в шпаргалке!
Ещё больше полезного в наших соц. сетях instagram, facebook, telegram
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Window.location.href is undefined on react-native #3790
Window.location.href is undefined on react-native #3790
Comments
Bug report
Describe the bug
When creating a new project using Expo-cli react-native and setting it up with a simple Supabase database, it crashes when building on Android. It runs fine on web version. The underlying issue is I believe with the goTrue.js library which takes window.location.href as argument but on mobile devices window.location is undefined see screenshot.
To Reproduce
Setup a new Expo project and install Supabase using the following client setup
import AsyncStorage from '@react-native-async-storage/async-storage' import from "@env"; const supabaseUrl = REACT_APP_SUPABASE_URL const supabaseAnonKey = REACT_APP_SUPABASE_ANON_KEY console.log(supabaseUrl, supabaseAnonKey) export const supabase = createClient(supabaseUrl, supabaseAnonKey, < localStorage: AsyncStorage >)
Run it using expo start and connect expo to an android device
Expected behavior
The project builds succesfully
Screenshots
System information
- OS: Windows + WSL
- Version of supabase-js: 1.25.2
- Expo version: 42.0.1
- Version of Node.js: v14.17.4
The text was updated successfully, but these errors were encountered:
Window location.href
The location.href property sets or returns the entire URL of the current page.
Syntax
Property Value
Parameter | Description |
URL | An absolute URL like: http://www.example.com/default.htm |
A relative URL like
default.htm
An anchor URL like
location.href=»#top»
Return Value
More Examples
Set the href value to point to an anchor within a page:
Set the href value to point to an email address (will open and create a new email message):
Browser Support
location.href is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
COLOR PICKER
Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.
Javascript location href undefined
Last updated: Dec 30, 2022
Reading time · 2 min
# 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.
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.