Extract the current DOM and print it as a string, with styles intact

前端 未结 8 1663
执笔经年
执笔经年 2020-12-07 08:19

I\'d like to be able to take my DOM, as is, and convert it to a string. Let\'s say I open up the inspector and make a change to the margin-left property of a particular ele

8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 09:10

    In case you want to capture the whole page, it is easier to just get all non-inline stylesheets and inline them.

    The approach in the accepted answer is magnificent, but quite slow and touches the whole document.

    I took the following approach to capture a page including style:

    1. document.documentElement.outerHTML;

    2. get all stylesheets from the document.styleSheets API

    Along the lines of:

    function captureCss(){
        var cssrules = "";
        var sheets = document.styleSheets;
        for(var i = 0; i\n"
                        }
                    }catch(e){
                        console.log(e);
                    }
                    continue;
                }
                for(var j=0;j\n"
                }
            }
        }
        return cssrules;
    }
    
    1. Add the captured cssrules as the first thing of the header in the outerHtml html text

    This way you get a self contained styled page.

    This is obviously less applicable for partial content.

提交回复
热议问题