I've made a search page for a client, but in this case the actual search page is in an iframe
and the user is presented with a decorative shell surrounding said iframe
, which passes its URL parameters to the iframe
, which then interprets them and performs a search. This is something I cannot change. It also presents me with the unique problem that if the user types into the search page's search bar to perform another search, the iframe refreshes but the shell page does not. This means the URL is now no longer relevant to the current search. How can I change the URL in the address bar without navigating away from this shell page? The whole point of this system is that there is less wait for the iframe
to refresh than the whole page, so refreshing the whole page would be counter-productive.
For anyone wanting just a code snippet, here's my final implementation of Ian's solution:
<?PHP
// ...
function buildTitleChanger($search) {
?>
window.top.history.pushState({search : "<?PHP echo str_replace("\"", "\\\"", $search); ?>"}, document.title, window.location.search);
window.top.document.title = document.title;<?PHP
}
// ...
?>
it's a little dirty with that inline PHP, but it works 100% of the time :3
HTML5 History API allows browsers to change the URL in browser address bar without reloading or refreshing the page using pushState function. The pushState method works similar to window.
You are able to change part of the URL with something like window.pushState
. Take a look at MDN's explanation:
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history
Browser compatibility: http://caniuse.com/history
A nice library that wraps these features and provides similar functionality in browsers that don't support it is history.js: http://balupton.github.io/history.js/demo/
An example from the MDN link:
Example
Suppose http://mozilla.org/foo.html
executes the following JavaScript:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
This will cause the URL bar to display http://mozilla.org/bar.html
, but won't cause the browser to load bar.html
or even check that bar.html
exists.
Suppose now that the user now navigates to http://google.com
, then clicks back. At this point, the URL bar will display http://mozilla.org/bar.html
, and the page will get a popstate
event whose state object contains a copy of stateObj
. The page itself will look like foo.html
, although the page might modify its contents during the popstate
event.
If we click back again, the URL will change to http://mozilla.org/foo.html
, and the document will get another popstate
event, this time with a null state object. Here too, going back doesn't change the document's contents from what they were in the previous step, although the document might update its contents manually upon receiving the popstate
event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With