如何在iframe或localhost中显示用户提交的网站的预览?

时间:2019-06-12 17:36:38

标签: javascript html django iframe localhost

我一直试图弄清楚如何在Django网站上显示用户提交的代码(html,css,javascript)。我可以让一个页面应用程序很好地显示在iframe中,例如一个带有CSS和javascript文件链接的html文件。

当用户有多个html页面并希望在它们之间链接时,就会出现问题。我还没有弄清楚如何在一个iframe中允许多个用户提交的html页面。是否可以使用iframe链接到另一个HTML页面?我可以在Django应用程序上设置本地主机环境来运行用户的网站吗(类似于CodeAcademy所做的事情)?

我尝试将用户代码写入iframe,这对于一个html文档来说效果很好。

let html = "<html><body>My HTML</body></html>";
let doc = document.getElementById('iframe').contentWindow.document;
doc.open();
doc.write(html);
doc.close();

我试图将多个html页面写入iframe或设置localhost环境以允许页面之间的导航(index.html,about.html,profile.html等)

如何使它正常工作?

1 个答案:

答案 0 :(得分:0)

我假设您有几组HTML字符串(每个页面)。



var getSiblings = function (elem,selector) {

    // Setup siblings array and start from the parent element of our input
    //this is under the assumption that you're only looking for an element that FOLLOWS #main/#secondary


    var sibling = elem,
    target = selector;

    // Loop through each sibling and return the target element if its found
    while (sibling) {

            if (sibling.hasClass(target) ) { //return the target element if its been located
                return sibling;
            }
        //since the element has not been located, move onto the next sibling
        if (sibling.next().length == 0) {
            return 0;
        } else {
            sibling = sibling.next();
        }

    }

    return 0; //failed to locate target
};

function firstOfClass(el,selector) {
   //our variables where startingPoint is #main/#secondary and target is what we're looking for
   var startingPoint = el,
   target = selector;
   while (startingPoint.parent().length) { 
//if it has a parent lets take a look using our getSiblings function
       var targetCheck = getSiblings(startingPoint, target);
       if ( targetCheck != 0 ) { //returns 0 if no siblings are found i.e we found a match
           return targetCheck;
       } else {
//lets keep ascending
           startingPoint = startingPoint.parent();
       }
   }
   return getSiblings(startingPoint, target);

}
//returns node if found, otherwise returns 0

firstOfClass( $('#main'),'valid-feedback' );

firstOfClass( $('#secondary'),'invalid-feedback' );

然后您将拥有一个将代码加载到iframe中的功能

var pages = {
    home: "<html><body>My Home page. <a href='parent.loadPage(\'about\')'>about me</a></body></html>",
    about: "<html><body>My About page. <a href='parent.loadPage(\'Home\')'>Home</a></body></html>"
};

然后您将调用该函数以加载主页...

function loadPage(page){
    let doc = document.getElementById('iframe').contentWindow.document;
    doc.open();
    doc.write(pages[page]);
    doc.close();
}

...并设置任何链接以调用该函数。

loadPage(page);