Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript history.PushState not working?

Tags:

I have this code here:

<script type="text/javascript">
function goFunction(){
  history.pushState("google.ca", "GOOGLE CANADA", "http://www.google.ca");
  return event.preventDefault();
}
</script>

and

<a href="#" onclick="javascript:goFunction();">GO</a>

when I click on my link, I get this error in my error log:

 Uncaught SecurityError: A history state object with URL 'http://www.google.ca/' cannot be created in a document with origin 'http://cowelllaserhair.com'. 

you can see this at: http://cowelllaserhair.com/test.html

What am I doing wrong?

Do I need to reference something?

Thanks, J

like image 467
user1269625 Avatar asked Nov 19 '13 18:11

user1269625


People also ask

Does history pushState reload page?

But this function is not intended to reload the browser. All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.

What is html5 pushState?

In an HTML document, the history. pushState() method adds an entry to the browser's session history stack.

What is the difference between pushState and replaceState?

replaceState() operates exactly like history. pushState() except that replaceState() modifies the current history entry instead of creating a new one. replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.


1 Answers

The URL argument to pushState should be relative to the current page, or or an absolute URL in your own domain. You can't push state cross-domain - it would be a major security flaw.

The MDN documentation says:

The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts her browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.

The URL parameter is most commonly left blank or set a relative URL on your own site, like #/hello.

like image 158
joews Avatar answered Sep 19 '22 16:09

joews