I am attempting to update the URL of an iframe dynamically, but I am encountering an issue: the Error message stating that an Unsafe value is being

Currently, I am attempting to dynamically alter the src of an iframe using Angular 2. Here is what I have 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';
});
}

}

Unfortunately, I encountered an error which reads:

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

I'm uncertain how else I can approach this issue. Any guidance or assistance would be greatly appreciated.

Thank you

Answer №1

Avoid using Jquery by utilizing Angular's 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>

For more information, visit the documentation Angular DomSanitizer

Answer №2

Start by removing any reliance on jQuery when diving into the world of Angular2 or newer versions.

Otherwise, you may find yourself unaware of how to achieve tasks in a more Angular-native manner.


Here's how you can accomplish the same task without using jQuery:

On the Component side:

// To prevent 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 prevent 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');
    }

}

On the Template side:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve error message from 400 error in AngularJS and WebAPI

Why am I having trouble reading the error message in AngularJS from this code snippet? ModelState.AddModelError("field", "error"); return BadRequest(ModelState); Alternatively, return BadRequest("error message"); return Content(System.Net.HttpStatusCod ...

Exploring TypeScript to get a ref with the Vue Composition API

The issue I'm facing is related to Vetur underlining 'null' in the following line: const firstRef = ref<HTMLElement>(null) <template> <input id="first" ref="firstRef"> <button type="button&q ...

In JavaScript, a "switch statement" retrieves a test value from a "input type text" by accessing the value using getElementByName.value

Attempting to test 7 possible values for the variable 'a' by passing it to a function from user input in seven 'input type text' boxes, then checking each value individually with clicks on 7 'input type image' elements. Howeve ...

Tips for sharing data between React components without causing re-renders or relying on JSX, such as through a function within functional components

As a beginner in react, I have been struggling to find answers to this issue. I am trying to figure out how to pass data from one functional component to another in react without actually rendering the child component. Does anyone know a solution for this ...

eliminate the gap in the MUI Accordion when it is expanded

How can I prevent the Accordion MUI component from moving and applying top and bottom margins to summary elements in expanded mode? I added the following code to the summary element but it doesn't seem to be working. Any suggestions on how to fix this ...

What steps should I take to resolve issues with importing Angular modules?

Success! import { MatInputModule } from '@angular/material/input' import { MatSelectModule } from '@angular/material/select' Having Issues import { MatInputModule, MatSelectModule } from '@angular/material' What could be c ...

What reasons might lead an object to be passed to a view as the exact term 'object' in Express.js?

Using nodejs, express, and ejs. I have a variable called 'result' which is properly defined. When I use console.log(result) within the router.get function on my index page, it outputs a correctly structured array of objects. After that, I rende ...

interactive navigation menu with countdown feature

Looking to create an HTML/jQuery dropdown menu, but encountering a problem. The goal is for the div to slide down when the mouse hovers over the "games" navigation button and only disappear after 5 seconds of the mouse being out, not instantly. Here's ...

Unexpected lack of tree shaking in Angular AOT compiled application

I am developing a module called MyCommonModule that consists of common components, services, etc. This module is designed to be shared across multiple Angular applications. Here is an example of a basic app that imports MyCommonModule, without directly re ...

Navigating resolvedUrl with getServerSideProps in the newest version of NextJS - a comprehensive guide

Is there a way to obtain the pathname without using client-side rendering? I have been searching for information on how to utilize the getServerSideProps function, but so far with no luck. Initially, I attempted to employ usePathname; however, this result ...

How can I load data from the server into CKEditor in React.js once the data is loaded?

Need to make changes in my code for editing an article item: const [contentEditor, setContentEditor] = useState(null); useEffect(() => { async function getLoadData(){ setitem(""); setContentEditor("" ...

Executing a PHP function within a Laravel controller using Ajax

In my Laravel project, I have a Controller named Clientecontroller that is working perfectly. It contains a method called listar() which retrieves client information. public function listar(Cliente $cliente) { $clientes = DB::table('clientes' ...

The issue arises from the fact that the Bootstrap modal fails to open automatically

Having trouble getting my bootstrap modal to open on page load, even though the button to trigger it is working fine. Here is my code: <div id="myModal" class="modal fade" role="dialog"> <div class=" ...

Having trouble rendering components due to conflicts between React Router and Semantic UI React

Below is the code in my App.js: import { useRecoilValue } from 'recoil'; import { authState } from './atoms/authAtom'; import { ToastContainer } from 'react-toastify'; import { ProtectedRoute } from './layout/ProtectedRou ...

Problems arising from the layout of the PrimeNG DataView component when used alongside Prime

I've been working with a PrimeNG DataView component that requires the use of PrimeFlex's flex grid CSS classes to set up the grid structure. One of their examples includes the following instructions: When in grid mode, the ng-template element ...

The browser freezes after a short delay following an Ajax request

I recently created an admin panel with notification alerts using Ajax. Initially, everything was working smoothly, but after a few minutes, the browser started freezing. I'm new to Ajax development, so I'm unsure what could be causing this issue. ...

The tooltip popup does not appear within the nz-tabs

Looking to enhance my two tabs with an info icon preceding the tab text, along with a tooltip popup that appears when hovering over the icon. Despite trying different methods, I have yet to achieve the desired outcome. <nz-tabset [nzLinkRouter]=&qu ...

Only one bootstrap collapse is visible at a time

Currently, I am using Bootstrap's collapse feature that displays content when clicking on a specific button. However, the issue I am facing is that multiple collapses can be open at the same time. I want to ensure that only one collapse is visible whi ...

Download CSV file directly in Internet Explorer 10 by choosing to open the file instead of saving it on your device

On my server, I have a link available to download a file: <a id="downloadCSVFile" runat="server" href="javascript:void(0)" onclick="parent.document.location = 'CSVFile.csv';">Download</a> I attempted this method as well: <a id=" ...

There appears to be some lingering content in the JQuery Mobile slide-out dialog box

My jQuery mobile slide out dialog box is experiencing an issue. The first time the slide out occurs, a comment box appears where users can enter comments and then submit them, followed by a "THANK YOU" message. However, when the user closes the dialog box ...