search
HomeWeb Front-endJS TutorialAngularJS uses $sce to control code security checks_AngularJS

Since browsers have same-origin loading policies, they cannot load files in different domains, nor can they access them using unsatisfactory protocols such as file.

In order to avoid security holes in angularJs, some ng-src or ng-include will be checked for security, so it is often encountered that ng-src in an iframe cannot be used.

What is SCE

SCE, that is, strict contextual escaping, my understanding is strict context isolation...The translation may not be accurate, but through literal understanding, it should be that angularjs strictly controls context access.

Since SCE is enabled by angular by default, it means that some unsafe behaviors will be prohibited by default, such as using a third-party script or library, loading a piece of HTML, etc.

This is indeed safe and avoids some cross-site XSS, but sometimes we want to load specific files ourselves, what should we do at this time?

At this time, you can use the $sce service to turn some addresses into safe and authorized links... Simply put, it is like telling the doorman that this stranger is actually my good friend and is very trustworthy, so there is no need to intercept it. !

Commonly used methods are:

$sce.trustAs(type,name);
$sce.trustAsHtml(value);
$sce.trustAsUrl(value);
$sce.trustAsResourceUrl(value);
$sce.trustAsJs(value);

The following ones are based on the first API. For example, trsutAsUrl actually calls trsutAs($sce.URL,"xxxx");

The optional value of type is:

$sce.HTML
$sce.CSS
$sce.URL //href in a tag, src
in img tag $sce.RESOURCE_URL //ng-include,src or ngSrc, such as iframe or Object
$sce.JS

Example from the official website: ng-bind-html

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-app="mySceApp">
  <div ng-controller="AppController">
   <i ng-bind-html="explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i>
  </div>
  <script type="text/javascript">
    angular.module('mySceApp',[])
    .controller('AppController', ['$scope', '$sce',
     function($scope, $sce) {
      $scope.explicitlyTrustedHtml = $sce.trustAsHtml(
        '<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
        'sanitization."">Hover over this text.</span>');
     }]);
  </script>
</body>
</html>

Example in action: ng-src link

<!DOCTYPE html>
<html>
<head>
  <title></title>
  <script src="http://apps.bdimg.com/libs/angular.js/1.2.16/angular.min.js"></script>
</head>
<body ng-app="mySceApp">
<div ng-controller="AppController">
  <iframe width="100%" height="100%" seamless frameborder="0" ng-src="{{trustSrc}}"></iframe>
</div>
  <script type="text/javascript">
    angular.module('mySceApp',[])
    .controller('AppController', ['$scope','$sce',function($scope,$sce) {
      $scope.trustSrc = $sce.trustAs($sce.RESOURCE_URL,"http://fanyi.youdao.com/");
      // $scope.trustSrc = $sce.trustAsResourceUrl("http://fanyi.youdao.com/");//等同于这个方法
     }]);
  </script>
</body>
</html>

There is still some time, let me introduce to you the ng-bind-html directive and $sce service in angular

One of the powerful features of angular js is its awesome feature of two-way data binding. Two things we often use are ng-bind and ng-model for forms. But in our projects we will encounter such a situation, the data returned by the background contains various html tags. Such as:

$scope.currentWork.description = “hello,
Where are we going today?
We use instructions like ng-bind-html to bind, but the result is not what we want. It’s like this

hello,

Where are we going today?

What to do?

For versions below angular 1.2, we must use the $sce service to solve our problem. The so-called sce is the abbreviation of "Strict Contextual Escaping". Translated into Chinese is "strict context mode" which can also be understood as safe binding. Let’s see how to use it.

controller code:

$http.get('/api/work/get&#63;workId=' + $routeParams.workId).success(function (work) {$scope.currentWork = work;});

HTML code:

<p> {{currentWork.description}}</p>

The content we return contains a series of html tags. The results are as mentioned at the beginning of our article. At this point we have to tell it to bind securely. It can be done by using $sce.trustAsHtml(). This method converts the value to one that is accepted by the privilege and safe for use with "ng-bind-html". So, we must introduce the $sce service in our controller

controller('transferWorkStep2', ['$scope','$http','$routeParams','$sce', function ($scope,$http, $routeParams, $sce) {
$http.get('/api/work/get&#63;workId=' + $routeParams.workId)
.success(function (work) {
  $scope.currentWork = work;
  $scope.currentWork.description = $sce.trustAsHtml($rootScope.currentWork.description);
});

html code:

<p ng-bind-html="currentWork.description"></p>

The result will be perfectly displayed on the page:

hello

Where are we going today?

We can also use it this way, encapsulate it into a filter and call it on the template at any time

app.filter('to_trusted', ['$sce', function ($sce) {
return function (text) {
  return $sce.trustAsHtml(text);
};
}]);

html code:

Select all and copy them into notes

<p ng-bind-html="currentWork.description | to_trusted"></p>
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment