Home  >  Article  >  Web Front-end  >  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
Patricia ArquetteOriginal
2024-10-21 13:22:31146browse

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>

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>

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>

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>
<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>

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!

Statement:
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