来自IE

时间:2018-02-06 11:50:54

标签: javascript angularjs internet-explorer iframe cross-browser

我有一个卑鄙的堆栈网站。我想动态构造一个包含有效html字符串的变量,然后在iframe中呈现它。经过一些研究,我尝试了以下代码:(JSBin

<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
        <script src="https://cdn.rawgit.com/jugglinmike/srcdoc-polyfill/master/srcdoc-polyfill.min.js"></script>
    </head>
    <body ng-app="app" ng-controller="Ctrl">
        <iframe srcdoc="{{content | toTrusted}}"></iframe>
        <script>
            var app = angular.module('app', []);
            app.controller("Ctrl", ["$scope", function($scope) {
                $scope.content = "<b>hello</b>";
            }])
            app.filter('toTrusted', ['$sce', function($sce) {
                return function(text) {
                    return $sce.trustAsHtml(text);
                };
            }]);
        </script>
    </body>
</html>

它在Chrome中运行良好,但在IE(例如IE 11)中无效,即使我使用src-polyfill

有没有人有解决方案?

1 个答案:

答案 0 :(得分:0)

app.directive('iframeDoc', [ '$sce', function ($sce) {
                return {
                    restrict:"A",
                    scope:{
                        iframeDoc:'='
                    }, 
                    link: function(scope, elem, attrs) {
                        elem.attr("srcdoc", $sce.trustAsHtml(scope.iframeDoc));
                        // Check browser to support scrdoc.
                        var  isSupportSrcDoc= !!("srcdoc" in document.createElement("iframe"));
                        if(!isSupportSrcDoc){
                            var  jsUrl = "javascript: window.frameElement.getAttribute('srcdoc');";
                            if (elem[0].contentWindow) {
                                elem[0].contentWindow.location = jsUrl;
                            }
                            elem.attr("src", jsUrl);
                        }
                    }
                };
            }])

在html中:

<iframe iframe-doc="content"></iframe>