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

What is causing the element to disappear in this basic Angular Material Sidenav component when using css border-radius? Check out the demo to see the issue in action

I have a question regarding the Angular Material Sidenav component. I noticed that in the code below, when I increase the border-radius property to a certain value, the element seems to disappear. <mat-drawer-container class="example-container" ...

Modifying button styles in Angular UI Datepicker

In this plunk, there is an Angular UI Datepicker with a template. I'm trying to customize the colors of the "Today", "Clear", and "Close" buttons by editing the popup.html. However, even after changing the classes in the code, the datepicker still sho ...

Leveraging the CSS-Element-Queries Library for emulating the functionality of CSS media queries

Recently, I used a nifty CSS-Element-Queries tool to perform basic element manipulations that trigger whenever the window is resized. In simple terms, my goal was to dynamically adjust an element's attribute based on the current width of the window â ...

Implementing Firebase pagination alongside Mui-Datatable pagination and sorting capabilities

I've been trying to implement server-side pagination and filtering for the Mui-Datatable to display my data, but I haven't been successful so far. Here are the snippets of code that I have been working on: One issue that I'm facing is that ...

Exploring the intersection of JavaScript and PostgreSQL: Leveraging timezones and timestamps

I'm a bit confused about how to properly use timestamps. For example, when a user creates an article, they can choose a PublishDate, and the system also automatically stores a CreateDate. a. Should I make both PublishDate and CreateDate timestamps wi ...

What is the best way to retrieve distinct objects based on LocId across all locations?

Encountering an issue while working on Angular 7: unable to return distinct or unique objects based on LocId. The goal is to retrieve unique objects from an array of objects containing all Locations. allLocations:any[]=[]; ngOnInit() { this.locationsServ ...

Receiving an error of "Undefined" when attempting to retrieve an array that is nested within an object

I've been struggling with the same question for a while now. Despite my knowledge of dot and bracket notation, as well as attempts using empty keys, I'm still unable to make it work. The situation involves a JSON array of objects obtained from an ...

The ultimate guide to loading multiple YAML files simultaneously in JavaScript

A Ruby script was created to split a large YAML file named travel.yaml, which includes a list of country keys and information, into individual files for each country. data = YAML.load(File.read('./src/constants/travel.yaml')) data.fetch('co ...

The component in React does not refresh after updating the state

I have a React page where I am displaying a list of quizzes fetched from an external API. There's also a "New Quiz" button that opens a dialog with a form for users to create a new quiz. My issue is with making the table re-render once the POST reque ...

Isolating Express.js Requests for Enhanced Security

In my Node.js Express app, multiple users send requests to the server for various actions such as earning points, changing email addresses, and interacting with other users. My server code utilizes several setTimeouts, leading me to question whether diffe ...

What is the best way to center my navigation bar without interfering with the mobile version's JavaScript functionality?

Just starting out with web development and stack overflow, so please bear with me if I struggle to explain the issue. I came across some JavaScript to make my website responsive on small screens (mobiles). However, I am having trouble centering my top nav ...

Defining JSON Schema for an array containing tuples

Any assistance is greatly appreciated. I'm a newcomer to JSON and JSON schema. I attempted to create a JSON schema for an array of tuples but it's not validating multiple records like a loop for all similar types of tuples. Below is a JSON sampl ...

Interactive mobile navigation featuring clickable elements within dropdown menus

I recently implemented a mobile nav menu based on instructions from a YouTube tutorial that I found here. Everything was working perfectly until I encountered an issue on the 'reviews list' page. The dropdown in the mobile nav is supposed to be ...

Is it possible to compare two charts in Chart.js in a way that avoids the issue of small values appearing as large as big values?

I am currently working on a production tracking page that features multiple charts. I want to avoid inconsistencies in tracking at first glance. Is there a way to achieve this using chart.js? If not, what would be the best approach to address this issue? ...

What is the best way to extract data from a series of nested JSON objects and insert it into a text field for editing?

I am facing a challenge with appending a group of nested JSON objects to a text field without hard coding multiple fields. Although I have used the .map functionality before, I am struggling to make it work in this specific scenario. const [questions, setQ ...

using javascript to target a specific css selector attribute

I have a CSS file with the following code: .datagrid table tbody td { color: #00496B; border-left: 1px solid #E1EEF4; font-size: 16px ;font-weight: normal; } Is there a way to use JavaScript to dynamically change the font size? The code below worked ...

Headers cannot be set once they have already been sent in NodeJS

Here is the code where I authenticate users in a group, push accounts into an array, and save them using a POST request on /addaccount. groupRouter.post('/addaccount', Verify.verifyOrdinaryUser, function(req, res, next) { Groups.findById(req.bod ...

Error message: Unable to iterate through a non-iterable object in React reducer

I find myself in a unique predicament and could use some assistance. userData : { isValidCheckup: true, accounts: { userAccount: [ { accountType: 'checkings', includeInCheckup: false }, { accountType: 'check ...

The functionality of ng-show/hide is not functioning properly when applied to dynamically generated HTML elements

Can dynamic HTML content work correctly with ng-show/hide functionality in AngularJS? An alternative solution is to use .show() and .hide() methods to display the desired plots. Scenario: I am adding plots dynamically to a specific HTML element ('sp ...

Prevent typing in text box when drawer is activated by pressing a button

update 1 : After removing unnecessary files, I need assistance with https://codesandbox.io/s/0pk0z5prqn I am attempting to disable a textbox. When clicking the advanced sports search button, a drawer opens where I want to display a textbox. The toggleDra ...