d-_-b
d-_-b

Reputation: 23211

How to use $sce.trustAsHtml when it contains <script> tags

I have an AngularJS component which loads HTML into its scope and uses ng-bind-html. I've noticed that <script> tags are not executing.

How can I get this example code to alert?

app.component('myComponent', {
    bindings: { 
        file: '<' 
    },
    controller: function($http, $sce) {
        var $ctrl = this;
        $ctrl.onChanges = function(changes) {
            $http.get($ctrl.file).then(function(response){
                $ctrl.html = $sce.trustAsHtml(response.data);
            });
        };
    },
    template: '<div><div ng-if="$ctrl.html" ng-bind-html="$ctrl.html"></div></div>'
});

The $http data that is being returned is:

<div> I am html <script>alert('I am a script')</script></div>

Or, what if I wanted to have a controller reference in the HTML?

<div ng-controller="myController"> I am html</div>

Upvotes: 1

Views: 314

Answers (1)

benbotto
benbotto

Reputation: 2439

Behind the scenes, $http.get is simply using XMLHttpRequest. Due to security constraints, and namely cross-site scripting, scripts added to the DOM dynamically (e.g. added after an XMLHttpRequest) do not execute. Hence, the only way to execute the script within your HTML is to find the script tag in the result, then call eval() on the contents.

Upvotes: 1

Related Questions