tsayen/dom-to-image

In Firefox getCssRules fails for external stylesheets

ghispi opened this issue · 4 comments

In firefox (41.0.2) getCssRules fails for stylesheets from external domains.

SecurityError: The operation is insecure.
util.asArray(sheet.cssRules || []).forEach(cssRules.push.bind(cssRules));

In particular it failed on such link:

<link href="//fonts.googleapis.com/css?family=Open+Sans:400italic,600italic,400,600" rel="stylesheet">

To workaround this I've applied such fix:

            function getCssRules(styleSheets) {
                var cssRules = [];
                var anchor = document.createElement('a');
                styleSheets.forEach(function (sheet) {
                    anchor.href = sheet.href;
                    if (anchor.hostname === window.location.hostname) {
                        util.asArray(sheet.cssRules || []).forEach(cssRules.push.bind(cssRules));
                    }
                });
                return cssRules;
            }

Hi! Thanks for reporting. Seems to me that your patch kind of skips the potentially problematic stylesheets. That could work, if the stylesheet you are skipping doesn't contain anything essential for the rendering itself, otherwise the rendered image will look differently. That also may be the only available workaround. I'll take a closer look at it

Well that was the only thing I found at the moment. Tomorrow I'll play with cross origin policy.
https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Cross-origin_network_access says that it should work with current code if the stylesheet has Content Type defined, type attrib which that particular link lacked. Although doc says it vary between browsers. Though this might give some clues for you.

Hi, in 1.0.5 I've added try/catch&log around the code that might throw that error. Don't know if that should remain there permanently, but let it be like that for now. If you're still interested in that issue, let me know what you think about it.