What is the reason for the filter not displaying the IFRAME?

I have a filter set up to automatically embed YouTube videos for user-generated content by searching for links and verifying if they are valid YouTube videos. If they are, the video should be embedded using standard iframe code; otherwise, it remains just a link. However, the filter is not outputting the expected iframe code. It seems like there might be security measures in place to prevent cross-site scripting attacks, but I'm unsure how to work around this issue.

function ytVidId(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp.$1 : false;
}

myapp.filter('parseUrls', function() {
    //with protocol
    var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/gi;
    return function(text, target, otherProp) {        
        if (text == null) {
            return "";
        }
        angular.forEach(text.match(urlPattern), function(url) {
            if(ytVidId(url)){
                text = text.replace(url, '<div class="video-container"><iframe src="//www.youtube.com/embed/'+ ytVidId(url) +'" frameborder="0" width="560" height="315"></iframe></div>');
            }else{
                text = text.replace(url, '<a target="' + target + '" href='+ url + '>' + url + '</a>');
            }

        });
        return text;        
    };
})

Example usage:

<span ng-bind-html="p.body | noHTML | newlines | parseUrls:'_blank'"></span>

Answer №1

If you are working with Angular, you will need to utilize the Strict Contextual Escaping (SCE) provider when passing HTML content.

For more information on the SCE provider, check out the documentation here.

Implementing this in your code can be done as follows (please note that this is a theoretical example and has not been tested):

function ytVidId(url) {
  var p = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
  return (url.match(p)) ? RegExp.$1 : false;
}    

myapp.filter('parseUrls', ['$sce', function() {
    //with protocol
    var urlPattern = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/gi;
    return function(text, target, otherProp) {        
        if (text == null) {
            return "";
        }
        angular.forEach(text.match(urlPattern), function(url) {
            if(ytVidId(url)){
                text = text.replace(url, $sce.trustAs('html', '<div class="video-container"><iframe src="//www.youtube.com/embed/'+ ytVidId(url) +'" frameborder="0" width="560" height="315"></iframe></div>'));
            }else{
                text = text.replace(url, $sce.trustAs('html', '<a target="' + target + '" href='+ url + '>' + url + '</a>'));
            }    

        });
        return text;        
    };
}])`

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

If you don't get the correct response from the $.ajax success function

I am utilizing the $.ajax function to retrieve content, however I am encountering an issue when attempting to display special tags from it. The data appears to be missing! This is how I am currently handling it: $(document).ready(function(){ $("button") ...

What steps can I take to ensure that my initial Ajax Get request is completed before proceeding with the next one?

Having two methods that return promises is not enough. I am attempting to make the second method execute only after the first one has obtained and manipulated data, but I have struggled to find a solution despite others asking this question before me. Here ...

AngularJs Datepicker malfunctioning after Data-dismiss operation

When using jquery datepicker in a AngularJs modal, it is important to initialize it correctly. Here is an example: <div class="col-md-2 rowdatepicker"> <label> RECORDING DATE </label> <input type="text" class="abs- ...

Sending JavaScript variables to an external CSS file

I've been searching for a solution without much luck. I must admit, my CSS skills are pretty basic. Currently, I am using Muxy.io to manage notifications for my livestreams. The platform allows customization of notifications through HTML and CSS file ...

What is the best way to arrange the keys of a JavaScript object in a customized

I am struggling to find a way to custom sort a JavaScript object properly. For example, I have the following object: var test = { 'yellow': [], 'green': [], 'red': [], 'blue': [] } And an array with values ...

Is it possible to achieve a fade effect in material-ui that truly hides the component instead of just disabling its visibility? If so, how can this be accomplished?

Currently, I am utilizing the component provided by material-ui, which can be found at material-ui. <Fade in={!randomizeFlag}> <Grid> <FormControlLabel control={<Switch onChange={this.handleStartValueFlag} & ...

Is there a way to configure a Mui textfield to only allow numeric input? It currently accepts numbers, the letter "e," and dashes

Take a look at my current code. <TextField error={values[1].error} fullWidth id="id" type="number" value={values[1].Id} placeholder='Enter ID' onChange={handleChange(1,'Id')} variant="outlined" inputProps={{min: 0,inputMode: &apos ...

Create a CSS popup alert that appears when a button is clicked, rather than using

Is there a way to customize CSS so that the popup alert focuses on a button instead of just appearing like this? I have implemented this type of validation for a text box: <div class="form-group"> <label class="control-label col-sm-3" for="judul ...

Efficiently generating and managing numerous toggle buttons in Reactjs with Material-ui ToggleButtons

Currently, I am exploring the idea of designing a sidebar that incorporates a variable number of toggle buttons generated from an object containing keys and values. However, I am encountering difficulties in utilizing the "key" value to adjust the corres ...

extract the text content from an object

I am trying to add an object to the shopping cart. The item contains a key/value pair as shown in the following image: https://i.stack.imgur.com/5inwR.png Instead of adding the title with its innerText using p and style, I would like to find another ...

Automated updating of Google Map markers

I am looking for a way to continuously update the marker on my Google Map to reflect my current position every 15 seconds using Jquery. Can anyone provide guidance on how to achieve this? Here is my code snippet: var x=document.getElementById("message"); ...

What is the best way to have setState function properly within setInterval? (currently functioning somewhat)

function timerFunction(){ const [time, setTime] = useState(10); var timeRemaining = 10; const myInterval = setInterval(() => { if (timeRemaining > 0) { timeRemaining = timeRemaining - 1; setTime(timeRemaining); } els ...

Modify the events JSON URL when the Full Calendar changes its display period

Whenever I switch between months or weeks, I need the JSON URL link to update accordingly. For example: The initial JSON URL is: /json/?start=2018-01-28&end=2018-03-10 When moving to the next month, the URL changes to: /json/?start=2018-02-25&am ...

What is the best way to conceal a Boostrap Navbar using jQuery?

Attempting to create a hidden side navbar using Jquery and Bootstrap 4. Struggling with the .on('click', ...) event handler for a button not hiding the sidebar as expected despite all files loading correctly according to the developer tools. Atte ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

Organize information within a single column of a table according to the heading using Angular

I have been working on implementing a sorting operation in a table for one or multiple columns. Consider the following table: When clicking on Heading 1, only Data 1 and Data 2 should be sorted. When clicking on Heading 2, Data 3 and Data 4 need to be sor ...

Guide on transferring three js variable to an HTML label element

For my project, I am looking to pass three js values to the label of a div. The desired output is: stWay: stProposer: stTime: hello John 2017-09-07 I have successfully programmed a button to make div1 a ...

Creating a live child component using React

My issue lies with the menu component, which is supposed to dynamically load elements in another container component. Unfortunately, the child elements are not being rendered. App.js import React, { Component } from 'react'; import './App. ...

Learn the technique of swapping out a portion of a string with a value from an input field in real-time

My webpage has a form on the left side where users can input text, and on the right is some static text. I want the text on the right to update automatically as the user types in the input field on the left. In my HTML code, it looks something like this - ...

Having difficulty deleting an entry from a flatList in a React Native component when using the filter method

I'm currently facing an issue with deleting an item from my flatlist in React Native. I've been attempting to use the filter method to exclude the list item with the ID entered by the user for deletion, but it's not working as expected. I&ap ...