我只想获取网站URL。不是从链接获取的URL。在页面加载时,我需要能够获取网站的完整、当前URL,并将其设置为一个变量,以便根据需要进行处理。
当前回答
添加结果以供快速参考
窗口位置;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
文档位置
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
窗口位置路径名
"/questions/1034621/get-the-current-url-with-javascript"
窗口.location.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
位置主机名
"stackoverflow.com"
其他回答
获取当前位置对象的方法是window.location。
将其与document.location进行比较,后者最初仅以字符串形式返回当前URL。可能是为了避免混淆,document.location被document.URL替换。
而且,所有现代浏览器都会将document.location映射到window.location。
实际上,为了跨浏览器安全,应该使用window.location而不是document.location。
获取当前页面URL:
window.location.href
Use:
window.location.href
正如评论中所指出的,下面这行行是有效的,但它对Firefox来说是错误的。
document.URL
请参阅DOMString类型的URL,只读。
好的,使用纯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.href属性返回当前页面的URL。
document.getElementById(“root”).innerHTML=“此页面的完整URL为:<br>”+window.location.href;<!DOCTYPE html><html><body><h2>JavaScript</h2><h3>窗口.location.href</h3><p id=“root”></p></body></html>
同样值得一提的是:
如果需要相对路径,只需使用window.location.pathname;如果要获取主机名,可以使用window.location.hostname;如果需要单独获取协议,请使用window.location.protocol此外,如果您的页面具有哈希标记,则可以获取如下内容:window.location.hash。
所以window.location.href一次处理所有内容。。。基本上:
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
//true
如果已经在窗口范围内,则不需要使用窗口。。。
因此,在这种情况下,您可以使用:
location.protocol
location.hostname
location.pathname
location.hash
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=“”即可。
推荐文章
- 一元加/数字(x)和parseFloat(x)之间的区别是什么?
- angularjs中的compile函数和link函数有什么区别
- 删除绑定中添加的事件监听器
- 很好的初学者教程socket.io?
- HtmlSpecialChars在JavaScript中等价于什么?
- React: 'Redirect'没有从' React -router-dom'中导出
- 如何在React中使用钩子强制组件重新渲染?
- 我如何使用Jest模拟JavaScript的“窗口”对象?
- 我如何等待一个承诺完成之前返回一个函数的变量?
- 在JavaScript中根据键值查找和删除数组中的对象
- 使嵌套JavaScript对象平放/不平放的最快方法
- 如何以及为什么'a'['toUpperCase']()在JavaScript工作?
- 有Grunt生成index.html不同的设置
- 文档之间的区别。addEventListener和window。addEventListener?
- 如何检查动态附加的事件监听器是否存在?