Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
424 views
in Technique[技术] by (71.8m points)

javascript - 在浏览器中更改URL而不使用JavaScript加载新页面(Change the URL in the browser without loading the new page using JavaScript)

How would I have a JavaScript action that may have some effects on the current page but would also change the URL in the browser so if the user hits reload or bookmark the new URL is used?

(我将如何执行一个JavaScript动作,该动作可能会对当前页面产生一些影响,但同时也会更改浏览器中的URL,因此,如果用户点击重新加载或添加书签,则会使用新的URL?)

It would also be nice if the back button would reload the original URL.

(如果“后退”按钮将重新加载原始URL,那也很好。)

I am trying to record JavaScript state in the URL.

(我正在尝试在URL中记录JavaScript状态。)

  ask by Steven Noble translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want it to work in browsers that don't support history.pushState and history.popState yet, the "old" way is to set the fragment identifier, which won't cause a page reload.

(如果您希望它在不支持history.pushStatehistory.popState浏览器中运行,则“旧”方法是设置片段标识符,这不会导致页面重新加载。)

The basic idea is to set the window.location.hash property to a value that contains whatever state information you need, then either use the window.onhashchange event , or for older browsers that don't support onhashchange (IE < 8, Firefox < 3.6), periodically check to see if the hash has changed (using setInterval for example) and update the page.

(基本思想是将window.location.hash属性设置为包含所需状态信息的值,然后使用window.onhashchange事件 ,或者对于不支持onhashchange旧版浏览器(IE <8,Firefox < 3.6),定期检查哈希值是否已更改(例如,使用setInterval )并更新页面。)

You will also need to check the hash value on page load to set up the initial content.

(您还需要检查页面加载时的哈希值以设置初始内容。)

If you're using jQuery there's a hashchange plugin that will use whichever method the browser supports.

(如果您使用的是jQuery,则有一个hashchange插件将使用浏览器支持的任何一种方法。)

I'm sure there are plugins for other libraries as well.

(我确定还有其他库的插件。)

One thing to be careful of is colliding with ids on the page, because the browser will scroll to any element with a matching id.

(要注意的一件事是与页面上的ID冲突,因为浏览器将滚动到具有匹配ID的任何元素。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...