Home > Web Front-end > JS Tutorial > How to Set iframe src Attribute from a Variable Safely in AngularJS?

How to Set iframe src Attribute from a Variable Safely in AngularJS?

Patricia Arquette
Release: 2024-10-21 13:22:31
Original
260 people have browsed it

How to Set iframe src Attribute from a Variable Safely in AngularJS?

Setting iframe src Attribute from Variable in AngularJS

In AngularJS, you may encounter issues when attempting to set the src attribute of an iframe from a variable. To address this, here's a step-by-step guide:

1. Inject the $sce Service

Inject the $sce (Strict Contextual Escaping) service into your controller to handle sanitization.

<code class="js">function AppCtrl($scope, $sce) {
  // ...
}</code>
Copy after login

2. Trust the Resource URL

Use $sce.trustAsResourceUrl within the controller to ensure the URL is safe.

<code class="js">$scope.setProject = function (id) {
  $scope.currentProject = $scope.projects[id];
  $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}</code>
Copy after login

3. Update the Template

In the template, bind the ng-src attribute to the trusted URL variable.

<code class="html"><iframe ng-src="{{currentProjectUrl}}"> <!-- content --> </iframe></code>
Copy after login

Example Code

<code class="js">function AppCtrl($scope, $sce) {
  $scope.projects = {
    // ...
  };

  $scope.setProject = function (id) {
    $scope.currentProject = $scope.projects[id];
    $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
  };
}</code>
Copy after login
<code class="html"><ul ng-repeat="project in projects">
  <li ng-click="setProject(project.id)">{{project.name}}</li>
</ul>

<iframe ng-src="{{currentProjectUrl}}">
  Something wrong...
</iframe></code>
Copy after login

Additional Notes

  • Use $sce.trustSrc for untrusted URLs.
  • The solution revolves around preventing Cross-Site Scripting (XSS) attacks by ensuring URLs are safe.

The above is the detailed content of How to Set iframe src Attribute from a Variable Safely in AngularJS?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template