How do I use Google Apps Script to change a CSS page to one with inline styles?

后端 未结 1 751
无人共我
无人共我 2020-12-11 08:59

Background...

I am trying to write a Google Apps Script to get the content of a Google Doc as HTML and use that HTML to create or update a web page in Google Sites.

1条回答
  •  萌比男神i
    2020-12-11 09:24

    There are numerous online tools that do this conversion, so you could leverage one of them from Google Apps Script. (If you only need to do this once in a while, why not just use one of those services?)

    Here's an example script, that builds on the getElementByVal() function from Does Google Apps Script have something like getElementById?.

    inline() function

    /**
     * Convert html containing  tags.
     *
     * @returns {Text}             Same HTML, converted to inline css.
     */
    function inline(htmlWstyle) {
      // Generate a POST request to inline css web tool.
      var payload =
      {
        "html" : htmlWstyle,
        "strip" : "checked"
      };
    
      // Because payload is a JavaScript object, it will be interpreted as
      // an HTML form. (We do not need to specify contentType; it will
      // automatically default to either 'application/x-www-form-urlencoded'
      // or 'multipart/form-data')
    
      var options =
      {
        "method" : "post",
        "payload" : payload,
        "muteHttpExceptions" : true
      };
    
      var url = "http://beaker.mailchimp.com/inline-css";
      var response = UrlFetchApp.fetch(url, options);
    
      // The html from this service is non-compliant, so we need
      // to massage it to satisfy the XmlService.
      var badlink = new RegExp('',"igm");
      var badmeta = new RegExp('',"igm");
      var badinput = new RegExp('',"igm");
      var xml = response.getContentText()
                        .replace(badlink,"" )
                        .replace(badinput,"" )
                        .replace(badmeta,"" )
                        .replace(/
    /g,"
    "); // So far, so good! Next, extract converted text from page.