3

I'm trying to create a link that will download a JSON file like so

Controller

$scope.url = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(obj));

View

<a href="url" download="download.json">download</a>

But when I inspect the generated HTML, unsafe: is prepended to the start of the href value, which prevents the link from working.

I've unsuccessfully tried using various methods of the $sce service to inform Angular that this URL should be trusted.

  • Maybe duplicate of this http://stackoverflow.com/questions/15606751/angular-changes-urls-to-unsafe-in-extension-page – webNeat May 04 '16 at 13:29

1 Answers1

4

Here's a working fiddle: https://jsfiddle.net/776gwzz8/2/

<script data-require="angular.js@1.5.5" data-semver="1.5.5" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<div ng-app="app" ng-controller="MainCtrl">
  <a href="{{jsonUrl}}" download="download.json">download</a>
</div>

<script type="text/javascript">
    var app = angular.module("app", []);

    app.config( [
        '$compileProvider',
        function( $compileProvider )
        {   
            $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|data|chrome-extension):/);
            // Angular before v1.2 uses $compileProvider.urlSanitizationWhitelist(...)
        }
    ]);

    app.controller("MainCtrl", ["$scope", function($scope) {

      var jsobObj = { name: 'Michelle', age: 28 };
      var jsonData = "text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(jsobObj));

      $scope.jsonUrl = 'data:' + jsonData;

    }]);
</script>
Kyle
  • 5,407
  • 6
  • 32
  • 47