在 AngularJS 中从受信任的来源插入 iframe [英] inserting iframe from trusted source in AngularJS

查看:23
本文介绍了在 AngularJS 中从受信任的来源插入 iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 ng-bind-html 将 iframe 插入带有 AngularJS 的页面 &即使是最简单的形式,我也无法让它工作.

Javascript

function Ctrl($scope) {$scope.showIt = '<iframe src="http://www.anything.com"></iframe>';}

我的 HTML:

解决方案

您需要使用 $sce 服务告诉 angular 在视图中呈现 html 内容

Angular Doc 说

<块引用>

$sce 是一项提供严格上下文转义服务的服务AngularJS.SCE 以 (a) 默认情况下安全的方式协助编写代码,并且(b) 对 XSS 等安全漏洞进行审计,点击劫持等更容易.

在此之前,您需要在您的应用中注入 ngSanitize 依赖

您可以通过两种方式使用 filtercontroller

HTML

使用过滤器<div ng-bind-html="showIt | toTrusted"></div>使用控制器<div ng-bind-html="htmlSafe(showIt)"></div>

JavaScript 代码

var app = angular.module('app', ['ngSanitize']).控制器('mainCtrl',函数($scope,$sce){$scope.showIt = '<iframe src="http://www.anything.com"></iframe>';$scope.htmlSafe = 函数(数据){返回 $sce.trustAsHtml(data);}}).过滤器('toTrusted',功能($ sce){返回函数(值){返回 $sce.trustAsHtml(value);};});

从 angular 1.2 开始,以下版本启用了 $sce 功能,您应该在 angular 的配置阶段启用/禁用它.

app.config(['$sceProvider', function($sceProvider) {$sceProvider.enabled(true);}]);

这是工作小提琴

Trying to use ng-bind-html to insert iframe into page with AngularJS & I can't get it to work it on even the simplest form.

Javascript

function Ctrl($scope) {
   $scope.showIt = '<iframe src="http://www.anything.com"></iframe>';
}

My HTML:

<div ng-bind-html="showIt"></div>

解决方案

You need to use $sce service to tell angular to render html content on view

Angular Doc says

$sce is a service that provides Strict Contextual Escaping services to AngularJS. SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier.

Before doing it, you need to inject ngSanitize dependency inside your app

You can do it in two way either using filter or controller

HTML

<div ng-app="app" ng-controller="mainCtrl">
    Using Filter
    <div ng-bind-html="showIt | toTrusted"></div>
    Using Controller
    <div ng-bind-html="htmlSafe(showIt)"></div>
</div>

JavaScript Code

var app = angular.module('app', ['ngSanitize']).
controller('mainCtrl', function ($scope, $sce) {
    $scope.showIt = '<iframe src="http://www.anything.com"></iframe>';
    $scope.htmlSafe = function (data) {
        return $sce.trustAsHtml(data);
    }
}).
filter('toTrusted', function ($sce) {
    return function (value) {
        return $sce.trustAsHtml(value);
    };
});

From angular 1.2 onwards $sce feature is enabled for below version you should enable/disable it in config phase of angular.

app.config(['$sceProvider', function($sceProvider) {
    $sceProvider.enabled(true);
}]);

Here is Working Fiddle

这篇关于在 AngularJS 中从受信任的来源插入 iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆