Smokey Dawson
Smokey Dawson

Reputation: 9230

Im trying to dynamically change the url of an iframe but Im getting an Error: Unsafe value used in resource URL

Im trying to dynamically change the src of an iframe using angular 2 Ive tried

HTML

<iframe class="controls" width="580" height="780" src="{{controllerSrc}}" frameborder="0" allowfullscreen></iframe>

COMPONENT.TS

import { Component, OnInit } from '@angular/core';

declare var jQuery: any;
const $ = jQuery;

export class VideoplayerComponent implements OnInit {
    controllerSrc: string;


ngOnit(){

    $('.button1').click(function(){
        this.controllerSrc = 'https://www.videoindexer.ai/embed/insights/0c7357bd5c/?widgets=people';
});
}

}

but Im getting an error that says

ERROR Error: unsafe value used in a resource URL context (see http://g.co/ng/security#xss)

not sure how else I can do this, any help would be appreciated,

Thanks

Upvotes: 1

Views: 8531

Answers (2)

Abinesh Joyel
Abinesh Joyel

Reputation: 2093

No need of Jquery. Use Angular DomSanitizer

import { DomSanitizer} from '@angular/platform-browser';
    export class VideoplayerComponent implements OnInit {
        controllerSrc: any;
         constructor(private sanitizer: DomSanitizer) {}

        ngOnit(){
           const url='https://www.videoindexer.ai/embed/insights/0c7357bd5c/?widgets=people';
           this.controllerSrc = this.sanitizer.bypassSecurityTrustResourceUrl(url);

        }
}


<iframe class="controls" width="580" height="780" [src]="controllerSrc" frameborder="0" allowfullscreen></iframe>

Please refer to the docs Angular DomSanitizer

Upvotes: 5

Vivek Doshi
Vivek Doshi

Reputation: 58553

First of all remove jQuery from your mind,while you are learning Angular2 or +,

Otherwise, you will never know how to do it in Angular way.


Here how you can achieve same thing without jQuery

Component side :

// to remove error : Error: unsafe value used in a resource URL context
import { DomSanitizer } from '@angular/platform-browser';

export class VideoplayerComponent implements OnInit {
    controllerSrc: string;
    constructor(sanitizer: DomSanitizer){}

    ngOnit(){
        this.controllerSrc = this.getSafeUrl('https://www.videoindexer.ai/embed/insights/0c7357bd5c/?widgets=people');
    }

    // to remove error : Error: unsafe value used in a resource URL context
    getSafeUrl(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url)
    }

    changeIframe() {
        this.controllerSrc = this.getSafeUrl('your-new-url');
    }

}

Template side :

<button (click)='changeIframe()'></button>

<iframe class="controls" width="580" height="780" [src]="controllerSrc" frameborder="0" allowfullscreen></iframe>

Upvotes: 3

Related Questions