Javascript AngularJS:如何解决“尝试在安全上下文中使用不安全值”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41996899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:48:47  来源:igfitidea点击:

AngularJS: How to resolve "Attempting to use an unsafe value in a safe context"?

javascripthtmlangularjstextarea

提问by STackers

When I tried to show my data as a text-html, it displayed in HTML format but when I refreshed the page, I am getting this error:

当我尝试将数据显示为 text-html 时,它以 HTML 格式显示,但是当我刷新页面时,出现此错误:

[$sce:unsafe] Attempting to use an unsafe value in a safe context.

[$sce:unsafe] 试图在安全上下文中使用不安全的值。

Here is my AngularJScode:

这是我的AngularJS代码:

data.attributes.task_name = $sce.trustAsHtml(data.attributes.task_name);

HTML

HTML

<span ng-bind-html="taskdata.attributes.task_name" data-html="true" title="{{reminder.attributes.message}}"></span>

回答by Mistalis

From the Angular documentation:

Angular 文档

The value provided for use in a specific context was not found to be safe/trusted for use.

AngularJS's Strict Contextual Escaping (SCE)mode (enabled by default), requires bindings in certain contexts to result in a value that is trusted as safe for use in such a context. (e.g. loading an AngularJS template from a URL requires that the URL is one considered safe for loading resources.)

This helps prevent XSS and other security issues. Read more at Strict Contextual Escaping (SCE)

You may want to include the ngSanitizemodule to use the automatic sanitizing.

未发现为在特定上下文中使用而提供的值是安全的/值得信赖的。

AngularJS 的严格上下文转义 (SCE)模式(默认情况下启用)需要在某些上下文中进行绑定,以产生一个值得信任的值,可在此类上下文中安全使用。(例如,从 URL 加载 AngularJS 模板要求该 URL 被认为可以安全地加载资源。)

这有助于防止 XSS 和其他安全问题。在严格上下文转义 (SCE) 中阅读更多内容

您可能希望包含ngSanitize模块以使用自动消毒。



You have to include ngSanitize:

你必须包括ngSanitize

Load it on index.html:

index.html上加载它:

<script src="lib/angular/angular-sanitize.min.js"></script>

Inject it as a dependency in your app.js:

将其作为依赖项注入app.js

angular.module('myApp', ['...', 'ngSanitize']);