[英]Live reloading iframe script on change
我正在使用HTML,CSS和JS代码设置一些编辑器。 更改时,每个代码都将重新加载到iframe中。 HTML和CSS代码可以完美地重新加载,插入到iframe主体中的脚本内部的JS代码无法正常工作,这可能是因为更新后它不会重新运行,但是我不知道该怎么做...
任何想法?
这是Plunker中的一个示例http://plnkr.co/edit/tpl:8rFfZljYNl3z1A4LKSL2?p=preview
的HTML
<div class="result">
<!-- RESULT -->
<style id="style"></style>
<script id="script"></script>
<script id="jQ" type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<iframe id="view" class="view"></iframe>
</div>
JS
var app = angular.module('plunker', []);app.controller('MainCtrl', function($scope) {
var style = document.getElementById('style');
var script = document.getElementById('script');
var jQ = document.getElementById('jQ');
var view = document.getElementById('view');
var viewDocument = view.contentDocument || view.contentWindow.document;
var body = viewDocument.getElementsByTagName('body')[0];
var head = viewDocument.getElementsByTagName('head')[0];
var widgets = [];
var loadScript = document.createElement('script');
loadScript.innerHTML = "var $ = parent.$; console.log('loaded');";
$scope.html = '<div id="test">Testing</div>';
$scope.js = 'console.log("More test");';
head.appendChild(jQ);
head.appendChild(loadScript);
head.appendChild(style);
body.appendChild(script);
$scope.$watch('html', function(nv){
body.innerHTML = nv;
body.appendChild(script);
});
$scope.$watch('js', function(nv){
script.innerHTML = nv;
});});
注意:手动设置时,代码似乎可以正常运行
解决了:
我找到了解决方法。 这是万一其他人需要的代码
setTimeout(updatePreview(codeHTML, codeCSS, codeJS), 300);
function updatePreview(codeHTML, codeCSS, codeJS) {
var view = document.getElementById('view');
var viewDocument = view.contentDocument || view.contentWindow.document;
var codeHTML = (codeHTML === undefined) ? '' : codeHTML;
var codeCSS = (codeCSS === undefined) ? '' : codeCSS;
var codeJS = (codeJS === undefined) ? '' : codeJS;
viewDocument.open();
viewDocument.write('<style type="text/css">' + codeCSS + '</style>');
viewDocument.write('<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>');
viewDocument.write(codeHTML);
viewDocument.write('<script type="text/javascript">' + codeJS + '</script>');
viewDocument.close();
}
在$ scope。$ watch的de editors中,这会传递更新后的值。
编织: http : //kodeweave.sourceforge.net/editor/#b6b39c95ec91f42950957a1ac8dc707f
我看到您能够解决您的问题,但是我有一个小建议。
如果用户像这样使用setTimeout或setInterval ...
setInterval((function() {
return $('body').css('background', newGradient())
}), 1000)
您的代码中的问题是它将添加到原始文字中,并且在这种情况下,setInterval函数将添加到上一个中。
因此,一个好主意是动态创建iframe并在其中添加代码。 这样,您可以更好地控制要添加到iFrame中的内容以及如何处理它。
document.querySelector(".preview").innerHTML = ""
var frame = document.createElement("iframe")
frame.setAttribute("id", "preview")
frame.setAttribute("sandbox", "allow-forms allow-modals allow-pointer-lock allow-popups allow-same-origin allow-scripts")
document.querySelector(".preview").appendChild(frame)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.