google-chromehtml-to-pdfwkhtmltoimage

htmlToImage Chrome 64 SecurityError: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules


The new Chrome 64 security update seems to have broken the htmlToImage libraries. None of the styling is correctly calculated and is rendered as if no styling was applied at all.

Does anyone know of a workaround / fix? Do I need to put my CSS on the server and allow CORS?


Solution

  • I just fixed this error.

    Forked the lib and made a pull request. Until it gets merged, you can use the forked repo: https://github.com/kmap-io/html-to-image

    by replacing the target of html-to-image in your package.json with:

    "html-to-image": "git+https://github.com/kmap-io/html-to-image.git"
    


    About the bug

    Chrome is complaining (throws an error) about trying to read a property that does not exist. Firefox also complains, but they only throw a warning, instead of an error. The fix consists of replacing

    if (sheet.cssRules) {
      ...
    

    with

    if (sheet.hasOwnProperty('cssRules')) {
      ...
    

    There is no downside (i.e.: when cssRules exists on sheet - which is a stylesheet - the script iterates through the rules and adds them to document, as supposed to).


    How to patch (until it gets merged).

    For some reason, simply replacing the library's repo with the fork in which I committed the change doesn't work for this package. I asked the lib's author to add instructions on how to build after a pull-request, as they state in the readme pull requests and contributions are welcome. Until then, here's how to apply the fix using patch-package:

    try {
    

    to

    if (sheet.hasOwnProperty('cssRules')) try {
    

    If you have a deployment script that builds your project from scratch, you'll need to apply the patches right before you call npm run build (or similar, depending on your stack):

    git apply --ignore-whitespace patches/*.patch
    

    That's about it.

    When the fix will be merged, you'll need to run:

    npx patch-package html-to-image --reverse