加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angularjs $sce

发布时间:2020-12-17 08:58:42 所属栏目:安全 来源:网络整理
导读:错误 iframe加载网页链报错 iframe class = "wh100" src = " {{ serverUrl }} " / iframe ( Error : [ $sce :insecurl ] Blocked loading resource from url not allowed by $sceDelegate ) 修改 这样就正常显示了 html head meta charset = "utf-8" script

错误

iframe加载网页链报错

<iframe class="wh100" src="{{serverUrl}}"></iframe>
(Error: [$sce:insecurl] Blocked loading resource from url not allowed by $sceDelegate)

修改

这样就正常显示了

<html> <head> <meta charset="utf-8"> <script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="myCtrl"> <iframe width="100%" height="100%" src="{{trustSrc(serverUrl)}}"></iframe> </div> <script> var app = angular.module('myApp',[]); app.controller('myCtrl',function($scope,$sce){ $scope.serverUrl = 'https://www.baidu.com/'; $scope.trustSrc = function(src) { return $sce.trustAsResourceUrl(src); } }); </script> </body> </html>

$sce

官方地址

$sce 服务是AngularJs提供的一种严格上下文转义服务

由于angular默认是开启SCE的,因此也就是说默认会阻止一些不安全的行为,比如你使用了某个第三方的脚本或者库、加载了一段html等等。

这样做确实是安全了,避免一些跨站XSS,但是有时候我们自己想要加载特定的文件,这时候怎么办呢?

此时可以通过$sce服务把一些地址变成安全的、授权的链接…简单地说,就像告诉门卫,这个陌生人其实是我的好朋友,很值得信赖,不必拦截它!

常用的方法有:

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

其中后面的几个都是基于第一个api使用的,比如trsutAsUrl其实调用的是trsutAs($sce.URL,”xxxx”);

其中type可选的值为:

$sce.HTML
$sce.CSS
$sce.URL //a标签中的href , img标签中的src
$sce.RESOURCE_URL //ng-include,src或者ngSrc,比如iframe或者Object
$sce.JS

官网解释2,3,5已经不用了,所以只研究下1和4的使用,4的使用文章开始已经给出

1的使用

<!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',$sce) { $scope.explicitlyTrustedHtml = $sce.trustAsHtml( '<span>Hover over this text.</span>'+"<span style='color:red;'>me<span>"); }]); </script>
</body>
</html>

参考

http://angular.narkive.com/lKJivzYA/iframe-with-ng-src-says-can-t-interpolate#post2
http://www.cnblogs.com/xing901022/p/5100551.html
http://blog.csdn.net/zcl_love_wx/article/details/51395211

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读