How to pass jquery object to history.pushState

var data = { url: $(this).attr('href'), selector: $(this) }; history.pushState(data, 'foo', $(this).attr('href')); 

When I do this, I get an error message:

Returned component failure code: 0x8000ffff (NS_ERROR_UNEXPECTED) [NsIDOMHistory.pushState]

If I change the selector to a string, the error will disappear ... But I need a jQuery object, so I can trigger it to click on the "popstate" event: s

+8
javascript jquery html5 history
source share
4 answers

Turning around on both Brian Nickel and GregL answers, you can solve this by doing $ ('#' + this.id) .attr ('href') ... as long as you have a DOM ID, as suggested by both guys in front of me.

Sometimes I get only the result:

 var $this = $('#'+this.id); //.... before hand ... 

and this allows me to be more creative with my id-ing, where, for example, I could have $('#'+this.id+'*locator*');

 ... id='abGGFather' ... id='abGFather' ... id='abFather' ... id='ab' 
0
source share

History data must be serialized. That is, it must be convertible to JSON. $(this) returns an array type object with DOM nodes that cannot be converted to JSON. You must look for another way to do what you are looking for.

Remember that the push state is just useful information and not intended for canonical ones. If the user cannot get the exact content by copying and pasting the URL into the address bar, you will have a problem.

+9
source share

You can save a link to a (un-serializable) rich object, and then restore it by reference.

See the demo version:

 var historyStateReference = { url1:{/*richobj*/}, url2:{/*richobj*/} } var serializableObj = { richObjRef = "url1", //otherProps } // pushState with a simple serializable Object history.pushState(serializableObj, null, "newPath"); // then later refrence it via history.state historyStateReference[history.state.richObjRef] ​ 
+3
source share

Consider assigning an identifier or other unique DOM node attribute that is represented by a jQuery object, then you can simply store the value of that identifier in your data object as a string that can be serialized.

If an element does not have a unique identifier, consider creating it and adding it to the element.

0
source share

All Articles