"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Set iframe src Attribute from a Variable Safely in AngularJS?

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

Published on 2024-11-08
Browse:582

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.

function AppCtrl($scope, $sce) {
  // ...
}

2. Trust the Resource URL

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

$scope.setProject = function (id) {
  $scope.currentProject = $scope.projects[id];
  $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
}

3. Update the Template

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

Example Code

function AppCtrl($scope, $sce) {
  $scope.projects = {
    // ...
  };

  $scope.setProject = function (id) {
    $scope.currentProject = $scope.projects[id];
    $scope.currentProjectUrl = $sce.trustAsResourceUrl($scope.currentProject.url);
  };
}
  • {{project.name}}

Additional Notes

  • Use $sce.trustSrc for untrusted URLs.
  • The solution revolves around preventing Cross-Site Scripting (XSS) attacks by ensuring URLs are safe.
Release Statement This article is reprinted at: 1729487777 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3