JavaScript를 사용하여 현재 URL을 가져오시겠습니까?
링크에서 가져온 URL이 아니라 웹사이트 URL만 가져오면 됩니다.페이지 로딩 시 웹사이트의 현재 URL 전체를 원하는 변수로 설정할 수 있어야 합니다.
용도:
window.location.href
코멘트에 기재되어 있듯이, 아래 행은 기능합니다만, 파이어폭스용의 버그가 붙어 있습니다.
document.URL
읽기 전용 DOMString 유형의 URL을 참조하십시오.
URL 정보 액세스
JavaScript는 브라우저의 주소 표시줄에 표시되는 현재 URL을 검색하고 변경할 수 있는 많은 방법을 제공합니다.이러한 메서드는 모두 오브젝트를 사용합니다.오브젝트는 의 속성입니다.Window지금 이 글을 수 요.Location다음을 읽고 오브젝트를 지정합니다.
var currentLocation = window.location;
기본 URL 구조
<protocol>//<hostname>:<port>/<pathname><search><hash>
프로토콜:인터넷의 리소스에 액세스하는 데 사용할 프로토콜 이름을 지정합니다(HTTP(SSL 없음) 또는 HTTPS(SSL 있음)).
호스트명:호스트 이름은 리소스를 소유하는 호스트를 지정합니다.예를들면,
www.stackoverflow.com서버는 호스트의 이름을 사용하여 서비스를 제공합니다.port: 인터넷 또는 기타 네트워크 메시지가 서버에 도착했을 때 전송되는 특정 프로세스를 인식하기 위해 사용되는 포트 번호.
경로 이름:경로는 웹 클라이언트가 액세스하려는 호스트 내의 특정 리소스에 대한 정보를 제공합니다.예를들면,
/index.html.search: 쿼리 문자열은 경로 컴포넌트에 이어 리소스가 어떤 목적으로 사용할 수 있는 정보 문자열(검색 파라미터 또는 처리할 데이터 등)을 제공합니다.
hash: URL의 앵커 부분. 해시 기호(#)를 포함합니다.
이것으로Location오브젝트 속성은 다음 URL 컴포넌트 모두에 액세스할 수 있으며 설정 또는 반환할 수 있습니다.
- href - URL 전체
- protocol - URL 프로토콜
- host - URL의 호스트 이름과 포트
- hostname : URL의 호스트명
- port - 서버가 URL에 사용하는 포트 번호
- pathname - URL 경로 이름
- search - URL 쿼리 부분
- hash - URL의 앵커 부분
- origin - the
window.location.protocol + '//' + window.location.host
당신이 답을 얻었길 바랍니다.
window.location현재 프레임에 관련되어 있는 Location 객체에 대한 읽기 및 쓰기 액세스.주소를 읽기 전용 문자열로 가져오려면document.URL은 ,은 , , , , , , , ,이다와 같아야 합니다window.location.href.
현재 페이지 URL을 가져옵니다.
window.location.href
네, 순수 JavaScript를 사용하면 현재 페이지의 전체 URL을 쉽게 얻을 수 있습니다.예를 들어, 이 페이지에서 다음 코드를 사용해 보십시오.
window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"
window.location.hrefpageproperty의 합니다.
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<p id="root"></p>
</body>
</html>
다음 사항도 언급하는 것이 좋습니다.
가 필요한 는, 「」를 해 .
window.location.pathname;「호스트명」을 사용해 .
window.location.hostname;할 에는 의전을 사용하시면 .
window.location.protocol- 페이지에 「 」가 경우는, 「 」입니다.
hash태그하면 '태그하다' 이렇게 수 있어요window.location.hash.
- 페이지에 「 」가 경우는, 「 」입니다.
★★★★★★★★★★★★★★★★★.window.location.href으로 다음과 같습니다츠키다
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
//true
, 「」, 「」를 사용합니다.window창 범위에 이미 있는 경우에는 필요하지 않습니다.
이 경우 다음을 사용할 수 있습니다.
location.protocol
location.hostname
location.pathname
location.hash
location.href
경로를 얻으려면 다음을 사용합니다.
console.log('document.location', document.location.href);
console.log('location.pathname', window.location.pathname); // Returns path only
console.log('location.href', window.location.href); // Returns full URL
Developer Tools를 열고 콘솔에 다음을 입력한 후 Enter 키를 누릅니다.
window.location
예: 아래는 현재 페이지의 결과 스크린샷입니다.
여기서 필요한 걸 가져오세요.:)
: ★★★★window.location.href.
와 같이, 「」는, 「」입니다.document.URL 업데이트할 때 업데이트되지 않음window.locationMDN을 참조해 주세요.
window.location.hrefURL을 .window.location.pathname을을을을 URL 을을을 을을을을을 。
해시 태그를 사용하여 현재 URL 위치를 가져올 수 있습니다.
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
j쿼리:
$(location).attr('href');
쿼리 문자열이 포함된 전체 URL의 경우:
document.location.toString()
호스트 URL의 경우:
window.location
// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""
host: "127.0.0.1:8000"
hostname: "127.0.0.1"
href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"
origin: "http://127.0.0.1:8000"
password: ""
pathname: "/projects/page/2"
port: "8000"
protocol: "http:"
search: "?name=jake&age=34"
username: ""
*/
url.searchParams.get('name')
// jake
url.searchParams.get('age')
// 34
url.searchParams.get('gender')
// null
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
currentPageUrlIs = this.href.toString().toLowerCase();
}else{
currentPageUrlIs = document.location.toString().toLowerCase();
}
위의 코드는 또한 다른 사람에게 도움을 줄 수 있다.
빠른 참조를 위해 결과 추가
window.location;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
document.location
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
window.location.pathname
"/questions/1034621/get-the-current-url-with-javascript"
window.location을 클릭합니다.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
위치.호스트명
"stackoverflow.com"
실제 URL 개체를 필요로 하는 경우 URL을 인수로 사용하는 유틸리티의 경우 다음과 같이 하십시오.
const url = new URL(window.location.href)
https://developer.mozilla.org/en-US/docs/Web/API/URL
Nikhil Agrawal의 답변은 훌륭합니다.콘솔에서 다양한 컴포넌트의 동작을 확인할 수 있는 간단한 예를 추가합니다.
또는 파라미터가 를 들어 AND 서버 요구를 실행하는 이, 「URL」( 「/」) 및 「」를 참조해 주세요.window.location.origin프로토콜과 옵션 포트를 유지하는 것이 최선입니다(Django 개발에서는 호스트 이름 등을 사용하면 포트가 고장나는 비표준 포트가 있는 경우가 있습니다).
여기에는 여러 가지 방법이 있습니다.
1:
location.href;
2:
document.URL;
3:
document.documentURI;
사용방법:
var url = window.location.href;
console.log(url);
jstl 의 URL 을 사용합니다.pageContext.request.contextPathAjax URL입니다.
url = "${pageContext.request.contextPath}" + "/controller/path"
: :의 http://stackoverflow.com/posts/36577223으로 알 수 있다http://stackoverflow.com/controller/path.
현재 위치 개체를 가져오는 방법은 다음과 같습니다.window.location.
이것과 비교document.location이 명령어는 원래 현재 URL만 문자열로 반환합니다.아마 혼란을 피하기 위해document.location로 대체되었다.document.URL.
그리고 최신 브라우저는 모두 맵입니다.document.location로.window.location.
실제로는 크로스 브라우저의 안전을 위해window.locationdocument.location.
location.origin+location.pathname+location.search+location.hash;
그리고.
location.href
같은 것을 합니다.
짧다
location+''
let url = location+'';
console.log(url);
는 이 페이지를 통해서 수 .location.href 다음 명령을
location.href.substring(0, location.href.lastIndexOf('/'));
JavaScript를 사용한 현재 URL 가져오기:
window.location.toString();
window.location을 클릭합니다.href
ID를 가진 특정 링크를 참조하는 경우 이 코드가 도움이 됩니다.
$(".disapprove").click(function(){
var id = $(this).attr("id");
$.ajax({
url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
type: "post",
success:function()
{
alert("The Request has been Disapproved");
window.location.replace("http://localhost/sample/page/"+id+"");
}
});
});
여기서 ajax를 사용하여 ID를 전송하고 window.location.replace를 사용하여 페이지를 리디렉션합니다.속성만 추가하다id=""기재한 바와 같이
경로를 얻으려면 다음을 사용합니다.
http://www.example.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
window.location.host www.example.com:8082
window.location.hostname www.example.com
window.location.port 8082
window.location.protocol http:
window.location.pathname index.php
window.location.href http://www.example.com:8082/index.php#tab2
window.location.hash #tab2
window.location.search ?foo=789
window.location.origin https://example.com
먼저 페이지가 완전히 로딩되었는지 확인합니다.
browser,window.location.toString();
window.location.href
그런 다음 URL, URL 변수를 가져와서 콘솔에 출력하는 함수를 호출합니다.
$(window).load(function(){
var url = window.location.href.toString();
var URL = document.URL;
var wayThreeUsingJQuery = $(location).attr('href');
console.log(url);
console.log(URL);
console.log(wayThreeUsingJQuery );
});
언급URL : https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript
'programing' 카테고리의 다른 글
| inversedBy와 mappedBy의 차이점은 무엇입니까? (0) | 2022.12.10 |
|---|---|
| Larabel 5.1에서 원시 쿼리를 실행하는 방법 (0) | 2022.12.10 |
| 비트 OR 0을 사용하여 숫자 바닥 설정 (0) | 2022.12.10 |
| 함수 내부에서 변수를 수정해도 변경되지 않는 이유는 무엇입니까? - 비동기 코드 참조 (0) | 2022.12.10 |
| MySQL 테이블 업데이트 및 중복 항목 무시 (0) | 2022.12.10 |



