1 回答

TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
let url = (window.location !== window.parent.location) ? document.referrer : document.location.href;
代碼中的這一行使得當(dāng)您在 iframe 中時(shí),document.referrer用作確定語言的 URL。
根據(jù)Document.referrer 上的MDN 頁面:
該Document.referrer屬性返回鏈接到此頁面的頁面的 URI。
在 內(nèi)<iframe>,Document.referrer最初將設(shè)置為與href父窗口的相同的值Window.location。
這意味著它可以在初始加載時(shí)正常工作,正如您所經(jīng)歷的那樣。據(jù)我所知,規(guī)范并沒有明確說明如何處理重新加載。這可能是瀏覽器行為差異的原因。認(rèn)為重新加載后它應(yīng)該是空的并不是太瘋狂,因?yàn)楫?dāng)時(shí)它不是從父頁面加載的。
另一種解決方案是使用window.parent.location.href,它始終引用iframe父窗口的 URL (在 document.referrer 和 window.parent.location.href 之間的區(qū)別中閱讀更多內(nèi)容)。
您的代碼行可能如下所示:
// 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;
添加回答
舉報(bào)