6

Cannot change URL using history.replaceState in a snippet

I recently answered a question here: UI-router change state without changing url and wanted to embed my answer as a snippet. When UI-Router kicks in and tries to apply the URL Hash according to the routing rules, the URL cannot be modified and angular triggers another digest cycle. It then goes into an infinite loop attempting to set the URL.

The relevant error message is as follows:

Error: Failed to execute 'replaceState' on 'History': A history state object with URL 'http://stacksnippets.net/js#/home' cannot be created in a document with origin 'null'.
    at Error (native)
    at Browser.self.url (https://code.angularjs.org/1.2.25/angular.js:4506:30)
    at https://code.angularjs.org/1.2.25/angular.js:9904:22
    at Scope.$eval (https://code.angularjs.org/1.2.25/angular.js:12701:28)
    at Scope.$digest (https://code.angularjs.org/1.2.25/angular.js:12513:31)
    at Scope.$apply (https://code.angularjs.org/1.2.25/angular.js:12805:24)
    at https://code.angularjs.org/1.2.25/angular.js:1447:15
    at Object.invoke (https://code.angularjs.org/1.2.25/angular.js:3966:17)
    at doBootstrap (https://code.angularjs.org/1.2.25/angular.js:1445:14)
    at bootstrap (https://code.angularjs.org/1.2.25/angular.js:1459:12)

The code in Browser.self.url (angular.js:4506) is doing the following:

  window.history.replaceState(null, '', "http://stacksnippets.net/js#/home");

Snippet that fails

This is the snippet I am trying to embed (run at your own risk, it will trigger digest loops infinitely). You can see this snippet working OK at plnk.co: http://plnkr.co/edit/w2aolrt9wdW3EFcEB3Lw?p=preview

    var app = angular.module('demonstrateissue', ['ui.router']);

    app.config(function($stateProvider, $urlRouterProvider) {
      $urlRouterProvider.otherwise("/home");
      $stateProvider.state({ 
        name: 'home', 
        url: '/home', 
        controller: function() { }, 
        template: '<h1>Home</h1><div ui-view></div>'}
      );
      $stateProvider.state({ 
        name: 'home.foo', 
        url: '/foo', 
        controller: function() { }, 
        template: '<h1>foo</h1>'}
      );
    });

    app.run(function($rootScope, $state, $location) {
      $rootScope.$state = $state;
      $rootScope.$location = $location;

      // This function will go to home.foo state but not change url
      $rootScope.gotofoo = function() { 
        $state.go("home.foo", {}, { location: false } );
      };
    });
    <!DOCTYPE html>
    <html>
      <head>
        <script data-require="angular.js@*" data-semver="1.2.25" src="https://code.angularjs.org/1.2.25/angular.js"></script>
        <script data-require="ui-router@*" data-semver="0.2.13" src="https://rawgit.com/angular-ui/ui-router/0.2.13/release/angular-ui-router.js"></script>
      </head>

      <body ng-app="demonstrateissue">
          <!-- click this -->
          <a href ng-click="gotofoo()">Go to foo dont change url</a>

          <div ui-view>/div>  
        
          <div class="header">
            Current URL: <b>{{$location.url()  }}</b> <br>
            Current State: <b>{{$state.current.name }}</b> <br>
            Current Params: <b>{{$state.params | json }}</b><br>
          </div>

      </body>
    </html>

1
  • UPDATE: Angular 1.2.27 and 1.3.6 seems to address the issue.
    – Chris T
    Dec 9, 2014 at 17:46

1 Answer 1

4

The error is most likely caused by the way HTML5 sandboxed iframes work and you can't directly control that (it's missing the allow-same-origin flag)

Taking a look at the source code for the iframe we can see that the only permissions it has is allow-scripts

I found here a nice summary of what the features of a sanboxed iframe are. Note the emphasis (mine)

Given an iframe with an empty sandbox attribute ( ), the framed document will be fully sandboxed, subjecting it to the following restrictions:

JavaScript will not execute in the framed document. This not only includes JavaScript explicitly loaded via script tags, but also inline event handlers and javascript: URLs. This also means that content contained in noscript tags will be displayed, exactly as though the user had disabled script herself. The framed document is loaded into a unique origin, which means that all same-origin checks will fail; unique origins match no other origins ever, not even themselves. Among other impacts, this means that the document has no access to data stored in any origin’s cookies or any other storage mechanisms (DOM storage, Indexed DB, etc.). The framed document cannot create new windows or dialogs (via window.open or target="_blank", for instance). Forms cannot be submitted. Plugins will not load. The framed document can only navigate itself, not its top-level parent. Setting window.top.location will throw an exception, and clicking on link with target="_top" will have no effect. Features that trigger automatically (autofocused form elements, autoplaying videos, etc.) are blocked. Pointer lock cannot be obtained. The seamless attribute is ignored on iframes the framed document contains.

The restrictions can be removed by applying the following flags

allow-forms allows form submission.

allow-popups allows (shock!) popups.

allow-pointer-lock allows (surprise!) pointer lock.

allow-same-origin allows the document to maintain its origin; pages loaded from https://example.com/ will retain access to that origin’s data.

allow-scripts allows JavaScript execution, and also allows features to trigger automatically (as they’d be trivial to implement via JavaScript).

allow-top-navigation allows the document to break out of the frame by navigating the top-level window.

In this case the history fails because it has no access or doesn't match the origin of the document. Similar as if you were to try changing the history for another domain. If for example you were to add the allow-same-origin flag before hitting the run button in the snippet editor, the code would work.

4
  • thanks for the analysis. Your answer doesn't explain how to use history API, but it certainly explains why it doesn't work in this context. Specifically, adding allow-same-origin to the iframe sandbox allows the code snippet to run. Two followups: 1) Do you believe the StackOverflow developers chose to omit allow-same-origin on purpose? 2) Can you think of any other workarounds in lieu of a change to the StackOverflow source code?
    – Chris T
    Dec 9, 2014 at 14:07
  • 3
    Sorry that I cannot offer much more help, but this answer is spot on. The restrictions are a necessary result of the security put into place by Stack Snippets in order to prevent hijacking your account / session / etc. Unfortunately this means that not all apps (such as Angular routing) will work as expected, especially if they depend on same-origin manipulation. While the issue is entirely in the iframe security, it might be worth pinging Angular to see if they can prevent the infinite loop for cross-origin routing as well. Sorry that I'm not more help.
    – Haney StaffMod
    Dec 9, 2014 at 15:20
  • @ChrisT Didn't want to go into too many details with the history API on meta so I kept it short and on the iframe problem x). I think Haney answered your followups. It prevents scripts inside the iframe from having access to unwanted places/APIs like setting or reading cookies and accessing the storage. Can't think of any other workaround but you could propose a feature-request to allow users to set the security level of the iframe. In that case advanced users could simply lower the level or set their own flags without editing the source code of SO.
    – Spokey
    Dec 9, 2014 at 15:37
  • Crazy timing, they JUST released 1.2.27 and 1.3.6 which fixes this issue: github.com/angular/angular.js/commit/…
    – Chris T
    Dec 9, 2014 at 17:43

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .