1 回答

TA貢獻1865條經驗 獲得超7個贊
let url = (window.location !== window.parent.location) ? document.referrer : document.location.href;
代碼中的這一行使得當您在 iframe 中時,document.referrer用作確定語言的 URL。
根據Document.referrer 上的MDN 頁面:
該Document.referrer屬性返回鏈接到此頁面的頁面的 URI。
在 內<iframe>,Document.referrer最初將設置為與href父窗口的相同的值Window.location。
這意味著它可以在初始加載時正常工作,正如您所經歷的那樣。據我所知,規范并沒有明確說明如何處理重新加載。這可能是瀏覽器行為差異的原因。認為重新加載后它應該是空的并不是太瘋狂,因為當時它不是從父頁面加載的。
另一種解決方案是使用window.parent.location.href,它始終引用iframe父窗口的 URL (在 document.referrer 和 window.parent.location.href 之間的區別中閱讀更多內容)。
您的代碼行可能如下所示:
// if parent and child href are equal, using either yields the same result
// if there is no parent, window.parent will be equal to window
// therefore, the conditional statement isn't necessary
let url = window.parent.location.href;
添加回答
舉報