![](/img/trans.png)
[英]Difference between window.location.href and this.router.url?
[英]What's the difference between window.open(url) and window.location.href = url on Firefox?
我正在嘗試構建一個bookmarklet,將當前url作為參數提供給另一個url。
但是我發現了這一點
javascript:(function(){window.open("http://www.somesi.te/some/thing?url="+encodeURIComponent(window.location.href))})()
這不起作用
javascript:(function(){window.location.href = "http://www.somesi.te/some/thing?url="+encodeURIComponent(window.location.href)})()
確實。 除了window.open
打開另一個窗口和window.location.href
更改位置的明顯區別之外,后者為什么會工作,而前者只是打開另一個窗口到原始位置?
這是在Firefox上。 有趣的是,在Chrome上工作正常。
這是安全的事嗎?
window.open()
和window.location.href
之間的區別在於open()
是窗口類的方法 , window.location
是窗口類的屬性 。
1. window.open()
是窗口類的一個方法
調用window.open()
方法實際上會創建一個窗口對象,該窗口對象可以保存在變量中並根據程序的要求進行操作。
要演示window.open()實際返回一個窗口對象,請考慮以下代碼:
var mywindow = window.open("http://google.com");
mywindow.name = "Awesome Window";
console.log(typeof(mywindow)); // --> "object"
console.log(mywindow.name); // --> "Awesome Window"
你的代碼打開一個不需要的窗口的原因是因為你正在調用window.open()
,它的唯一目的就是打開一個新窗口。
2. window.location
是窗口類的只讀屬性 。
雖然window.location
是一個只讀屬性,但window.location
有一個內置的快捷方式功能,允許window.location
可分配,這與調用window.location.assign()
具有相同的效果,但不返回一個窗口對象,但使用根窗口對象分配一個新的URL,導致新分配的URL被加載到瀏覽器窗口中,在該窗口中調用了分配位置的javascript。
如果您正在創建bookmarket腳本,那么使用window.location
是獲取當前窗口的url並將其分配給程序的url字符串的更好方法。
您可能會發現在不同瀏覽器中遇到意外行為的原因是窗口對象沒有正式的公共標准集,因此每個瀏覽器選擇在幕后實現它的方式可能會有所不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.