Reputation: 1295
I am trying to to deep link in my site. what i mean by this is that i can go to a url like
http://test.madeup.com/?campaign=funkyNew
If go to this it will change the page display and bring the funkynew campaign to the top.
I have been going through the example of history.js and have a couple of questions.
so the example code is something like this
// Establish Variables
var History = window.History, // Note: We are using a capital H instead of a lower h
State = History.getState(),
$log = $('#log');
// Log Initial State
History.log('initial:', State.data, State.title, State.url);
// Bind to State Change
History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
// Log the State
var State = History.getState(); // Note: We are using History.getState() instead of event.state
History.log('statechange:', State.data, State.title, State.url);
alert("stateChanged - run function");
});
// Prepare Buttons
var
buttons = document.getElementById('buttons'),
scripts = [
'History.pushState({state:1,rand:12345}, "Test", "?campaign=funkyNew"); '
],
buttonsHTML = '';
// Add Buttons
for ( var i=0,n=scripts.length; i<n; ++i ) {
var _script = scripts[i];
buttonsHTML +=
'<li><button onclick=\'javascript:'+_script+'\'>'+_script+'</button></li>';
}
buttons.innerHTML = buttonsHTML;
and this works by clicking on the button changing the url and then the variables are shown. This works ok.
What I need to do is go direct to the url with the funkynew and get the variables and get it to run a function.
Obviously, it wont work now because history is only created when the buttons are pushed - so how could I go about having these there at the beginning so that if I go direct to the funkyCampaign ie from another url I see the variables
does this make sense?
Thanks for any help
Dan
Upvotes: 0
Views: 618
Reputation: 2079
Not sure if you figured out a way to deep linking.
The below works for me. It basically get the params from url and forms a state and replaces the current(initial) state with it.
// Bind to State Change
History.Adapter.bind(window,'statechange',function(){
// Log the State
var State = History.getState();
History.log('statechange:', State.data, State.title, State.url);
alert("stateChanged - run function");
});
var utils = utils || {};
utils.getParameterByName: function (name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
//On page load route to appropriate screen
if(urlParamSection = utils.getParameterByName('section')){
History.replaceState({
section: urlParamSection
}, // This is state's data
'MySite - ' + urlParamSection.toUpperCase(), //Title to the state
window.location.protocol+"//"+window.location.host + "?section=" + urlParamSection // this is actually the page load url
);
}
Upvotes: 2