對於新的Web應用程序,我想在用戶單擊鏈接時修改歷史記錄,以便URL更改,但頁面沒有重裝。我將在Ajax中加載一部分頁面。這可以很容易地完成並記錄在很多地方(例如,Mozilla,diveintohtml5,Stack Overflow)。讓用戶在同一站點內手動導航到新的URL,而不是刷新頁面
但是,我想知道是否有一種方法可以讓用戶在不重新加載頁面的情況下修改URL。例如,有人給他們在同一個域中的鏈接,或者他們想出於某種原因手動輸入URL。我想以與我單擊鏈接時相同的方式加載新頁面 - 無需重新加載頁面,而是修改歷史記錄。
有沒有辦法做到這一點?下面是我在想什麼要點,但神奇的功能getNewURLFromEvent
,preventUserFromActuallyLeavingPage
,並carryOn
需要執行(如果可能):
window.addEventListener('unload', function(event) {
var newURL = getNewURLFromEvent(event);
if (isInThisDomain(newURL)) {
preventUserFromActuallyLeavingPage();
window.history.pushState('content', 'title', document.URL);
} else {
// Let the user leave (the internet is a free place after all)
carryOn();
}
});
function isInThisDomain(URL) {
/* Would probably implement some error checking here too */
var thisDomain = document.URL.match(/:\/\/(.+?)\//)[1],
thatDomain = URL.match(/:\/\/(.+?)\//)[1]);
return thisDomain === thatDomain;
}
function getNewURLFromEvent(e) {
/* Figure out where the user want's to go */
}
function preventUserFromActuallyLeavingPage() {
/* Since we're changing the content it still looks
like the user's leaving, but really they haven't
gone anywhere from the site's perspective */
}
function carryOn() {
/* Essentially do nothing, but maybe more magic is needed? */
}
如果你覺得這是一個壞主意 - 但仍可能 - 請解釋爲什麼這是一個壞主意。
謝謝。
我想說即使有可能這可能是一個壞主意,如果用戶不期望這種行爲。 – 2013-03-19 21:39:39
那麼,如果我在https://github.com/nnnick/Chart.js上並單擊Chart.js,則URL將更改爲https://github.com/nnnick/Chart.js/blob/master/Chart .js和我正在查看的文件更改,但頁面的其餘部分保持不變。我在想如果我從第一個URL中輸入第二個URL,爲什麼不具有相同的功能? – redbmk 2013-03-19 21:53:13