简体   繁体   中英

Is there any way to turn a webpage that is styled partially with Javascript into pure HTML and CSS?

I have a React webpage with HTML components, some of which are styled with CSS, and others of which are styled with javascript ( Glamor ). What I'd like is HTML code with inline CSS that exactly replicates the look of the page to send in an email.

I know I can inline CSS with a package like Styliner , but I'm wondering if it's possible to somehow convert the js-defined Glamor styles into plain CSS and inline that as well?

If it isn't possible, then I will probably explore a different route (taking a PDF snapshot of the page). Appreciate the help!

You can iterate document.styleSheets and set each CSS rule at style attribute of the element. CSS pseudo elements and classes set at HTML style attribute of HTML element are currently not rendered within the document .

Looking at the documentation, glamor seems to create style sheets in the DOM of the page using the package. So after all calls to glamor have finished, traversing document style sheets should pick up the results. A linked example of looking through style sheets is not exactly what is needed. Here is a example (modified from old style code) of getting CSS definitions as text that works in a browser:

function cssStyleRules(sheets) {
    var sheet;
    var list;
    var rule;
    var text="";

    if(sheets) {
        for(var i = 0; sheet = sheets[i++]; ) {
            list = sheet.cssRules;
            for( var j = 0; j < list.length; ++j) {
                rule=list[ j];
                if(rule.type == 1)  { // styleRule
                    text += rule.cssText + '\n';
                }
            }
        }
    }
    return text;
}
var css = cssStyleRules( document.styleSheets);
// write css to a file in a headless browser

Obviously the code needs to be run in a headless browser on the server which writes the CSS text to a file before being processed by Styleliner.


Update:

You've commented on not being able to get style sheets back from the headless browser as expected. This could be the browser's fault, but checking Glamor.md's implementation.md turned up

insert into stylesheet

We use our own abstraction over the browser's stylesheet to insert the rule into the dom. This abstraction also works on node, letting us do stuff like SSR, etc. It also uses different modes of inserting styles based on the environment, as detailed here

... but the link is a stub. I would suggest looking into implementaion details further and particularly what they mean by "this abstraction also works on node".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM