如何避免AngularJs为javascript添加前缀“unsafe”?
发布时间:2020-12-17 16:56:34 所属栏目:安全 来源:网络整理
导读:我尝试将bookmarklet按钮添加到我的网站,并在控制器中生成链接. 模板部分: a id="bookmarklet" class="bookmarklet" onclick="alert('Drag and drop me to the bookmarks bar');return false;" href="{{getCode()}}" + Add /a 控制器部分: $scope.getCode
我尝试将bookmarklet按钮添加到我的网站,并在控制器中生成链接.
模板部分: <a id="bookmarklet" class="bookmarklet" onclick="alert('Drag and drop me to the bookmarks bar');return false;" href="{{getCode()}}"> + Add </a> 控制器部分: $scope.getCode = function () { var code = 'javascript:(function(){s=document.createElement('SCRIPT');s.type='text/javascript';' + 's.src='http://localhost:9000/scripts/bookmarklet/bookmarklet.js?x=' + ($scope.user.id) + '';' + 'document.getElementsByTagName('head')[0].appendChild(s);document.sc_srvurl='http://localhost:8080'})();' ; return code; }; 但是我在编译后得到了以下内容: <a class="bookmarklet" href="unsafe:javascript:(function(){s=document.createElement('SCRIPT');s.type='text/javascript';s.src='http://localhost:9000/scripts/bookmarklet/bookmarklet.js?x=5517325d40c37bc2bfe20db6';document.getElementsByTagName('head')[0].appendChild(s);document.sc_srvurl='http://localhost:8080'})();"> + Add </a> 链接以“不安全”开头,我无法告诉角度如何信任此链接. 这个答案 – Angular changes urls to “unsafe:” in extension page建议将协议添加到白名单. 我可以告诉angularjs以避免使用$sce添加前缀“unsafe”吗?不幸的是,文档对我来说并不清楚,$sce.trustAsJs(代码)对我没有帮助. !EDIT Angular版本是1.4.1. 解决方法
尝试通过编写自定义指令来规避限制:
var app = angular.module('myApp',[]); app.directive('bookmarklet',function () { return { restrict: 'A',scope: {},link: function($scope,element,attrs) { if (element[0].tagName !== 'A') { return; // simply do nothing (or raise an error) } element[0].href = 'javascript:alert("It works in 1.4.1,too!")'; } }; }); 用法: <div ng-app="myApp"> <a href="#foo" bookmarklet>click me</a> </div> 我还创建了一个小提琴演示来测试它:http://jsfiddle.net/t0acdxcL/1/ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |