Security Error when using the JavaScript map function in FireFox

My current dilemma involves using a JavaScript code to extract the above-the-fold CSS from my websites. Surprisingly, it functions flawlessly on Google Chrome. However, when I attempt to execute it on Firefox, an infamous 'SecurityError' occurs:

**SecurityError: The operation is insecure.**
findCriticalCSS/outputCss< 
map self-hosted
findCriticalCSS
<anonym>
<anonym>

Displayed below is the script that I'm employing:

function post(path, params, method) {
method = method || "post"; // Defaulting to post for method if unspecified.

// Assuming no library usage for the following code snippet.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);

for(var key in params) {
    if(params.hasOwnProperty(key)) {
        var hiddenField = document.createElement("input");
        hiddenField.setAttribute("type", "hidden");
        hiddenField.setAttribute("name", key);
        hiddenField.setAttribute("value", params[key]);

        form.appendChild(hiddenField);
     }
}

document.body.appendChild(form);
form.submit();
}

(function() {
    function findCriticalCSS(w, d) {
        var formatPseudo = /([^\s,\:\(])\:\:?(?!not)[a-zA-Z\-]{1,}(?:\(.*?\))?/g;
        var targetHeight = 900;
        var criticalNodes = [];

    var walker = d.createTreeWalker(d, NodeFilter.SHOW_ELEMENT, function(node) { return NodeFilter.FILTER_ACCEPT; }, true);

    while(walker.nextNode()) {

        var node = walker.currentNode;
        var rect = node.getBoundingClientRect();
        if (rect.top < targetHeight) {
            criticalNodes.push(node);
        }
    }
    console.log("Located " + criticalNodes.length + " critical nodes.");

    var stylesheets = document.styleSheets;
    console.log("Encountered " + stylesheets.length + " stylesheet(s).");

    var outputCss = Array.prototype.map.call(stylesheets,function(sheet) {
        var rules = sheet.rules || sheet.cssRules;

        if (rules) {
            return {
                sheet: sheet,
                rules: Array.prototype.map.call(rules, function(rule) {
                    try {
                        if (rule instanceof CSSMediaRule) {
                            var nestedRules = rule.rules || rule.cssRules;
                            var css = Array.prototype.filter.call(nestedRules, function(rule) {
                                return criticalNodes.filter(function(e){ return e.matches(rule.selectorText.replace(formatPseudo, "$1"))}).length > 0;
                            }).map(function(rule) { return rule.cssText }).reduce(function(ruleCss, init) {return init + "\n" + ruleCss;}, "");
                            return css ? ("@media " + rule.media.mediaText + " { " + css + "}") : null;

                        } else if (rule instanceof CSSStyleRule) {
                            return criticalNodes.filter(function(e) { return e.matches(rule.selectorText.replace(formatPseudo, "$1")) }).length > 0 ? rule.cssText : null;
                        } else {
                            return rule.cssText;
                        }
                    } catch(e) {
                        /*console.error("Improper CSS rule ", rule.selectorText);
                            throw e;*/
                    }
                }).filter(function(e) { return e; })
            }
        } else {
            return null;
        }
    }).filter(function(cssEntry) {return cssEntry && cssEntry.rules.length > 0 })
    .map(function(cssEntry) {try {  return cssEntry.rules.join(""); }catch(e){return;}})
    .reduce(function(css, out) {return out + css}, "")

    console.log(outputCss.replace(/\n/g,""))
}

findCriticalCSS(window, document);
})()

I suspect that the error might be related to external CSS files within my site. Does anyone have insights on how to diagnose and resolve this issue?

Appreciate any assistance rendered, J. Doe ;)

Answer №1

If you encounter an error when trying to access stylesheets from a different domain, it could be due to the following line of code:

var rules = sheet.rules || sheet.cssRules;

According to MDN documentation:

When attempting to retrieve cssRules from a stylesheet that is loaded from a separate domain, certain browsers may throw a SecurityError.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring SVGO CLI: A guide to inspecting SVGs across various directories

Currently, I am utilizing the SVGO CLI script to transform some icons within my project. Specifically, these icons are located in two separate folders - assets/icons/dark-mode and assets/icons/light-mode. My goal is to navigate through both of these folder ...

Unlock the power of nested dynamic content creation with JavaScript

Every time I attempt to use getelementbyid on a dynamically loaded div, I receive null as the result. This occurs even after trying both window.onload = function () { and $(window).load(function() { index.html: <main > <div id="main-div"> ...

Ensuring the bootstrap footer remains anchored at the bottom of the page content

I've been struggling for 3 days to get the footer to stay at the bottom of my webpage content. I've searched through many similar questions, but still can't find a solution. Here is my code: .container{position:relative;} footer{position: ...

Change the css code to override the color of the background material

Hey there, I'm facing an issue with overriding the background color of a material element. I've tried several methods but can't seem to get it to change. After inspecting the element on the web browser, I found the CSS code that controls th ...

displaying outcomes as 'Indefinite' rather than the anticipated result in the input field

I need to automatically populate values into 4 text fields based on the input value entered by the user. When the user exits the input field, a function called getcredentials() is triggered. This function, in turn, executes Python code that retrieves the r ...

Issues detected with the functionality of Angular HttpInterceptor in conjunction with forkJoin

I have a Service that retrieves a token using Observable and an HttpInterceptor to inject the token into every http request. It works seamlessly with a single request, but when using forkJoin, no response is received. Here is the code for the interceptor: ...

How can I set a value using document.getElementById(idPopUPImage).innerHTML to create a static popup in Leaflet?

I added a leaflet map to my project which you can find on Codpen In the map, I've included a button key that displays an image in a popup when clicked. However, after closing the popup and reopening it, the image doesn't show unless I click the ...

Button appears and disappears sporadically while browsing in Safari

I created a slider using SCSS, JavaScript, and HTML. You can view the demo at this link: https://jsfiddle.net/rr7g6a1b/ let mySlider = { initializeSlider: function (options) { let slider = options.container; let slides = slider.querySelectorAll( ...

forward to a different link following the backend script execution

I am facing a challenge with the signup.php page which includes a Facebook login button. The structure of the page is as follows: <?php if(!isset($_SESSION['logged_in'])) { echo '<div id="results">'; echo '<!-- ...

Issue: Unable to create the restangular module because: the variable '_' is not defined

Upon integrating Restangular into an existing website, I encountered a JavaScript error that stated: Failed to instantiate module restangular due to: '_' is undefined I'm unsure of what this means. Can anyone clarify why '_' is ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

Streaming large files with Node.js can lead to significant memory consumption and potential memory errors like OOM

My current project involves using node.js to download large files (300MB) from a server and then piping the response to a file write stream. While I have a good understanding of how pipes work in Node.js, I am encountering an issue where the memory usage o ...

Eliminating unnecessary CSS from the codebase of a website

Currently, I am making adjustments to a website template that I downloaded for free online. I have noticed that even if I delete a div from the code, the corresponding CSS styles remain in one or more files. Is there any tool available that can automatic ...

When utilizing jQuery, I implemented this code but it does not display anything. I am unsure of the error within the code

When using jQuery, I implemented the following code snippet but it doesn't display anything. What could be causing this issue? // $.ajax({ // URL:"https://dog.ceo/api/breeds/image/random", // method:"GET", // ...

Information released by JavaScript through AJAX and JSON

Hello everyone, I've been trying to merge two different Ajax codes together and it's been quite a challenge. As a novice, I know I may sound ridiculous but I really need some help... My goal is to convert an array into JSON and display the data ...

Discovering the current active link and anchor tag details using jQuery in an unordered list

I am currently utilizing jQuery to work with 4 anchor tags inside an unordered list, and I would like to be able to determine the "current active link" when a user performs a search. This way, I can execute my query based on the selected anchor tag. How ca ...

What methods can be used to modify the behavior of tiptap when pasting plain text?

Currently, my goal is to create a visual editor by utilizing the tiptap library. Although v2 of tiptap is more commonly used, there are instances where v1 is necessary. However, I encountered an issue with tiptap's behavior when pasting plain text, ...

React Component is not functioning with the timer running

I am currently developing a basic timer app using React. Here is the code snippet I have so far: import React from "react" const timer = (props) => { let time = 25; let processStatus = props.timerProcessStatus; // set to true if(processSta ...

The JavaScript syntax dollar sign

I am currently studying a JavaScript source code and it's my first time writing JavaScript. I find some of the syntax confusing. <script id="source" language="javascript" type="text/javascript"> $(function () { window.onload=function() ...

JavaScript code does not seem to be functioning properly on my computer, but it works perfectly fine on

While the code functions perfectly in JSFiddle, it seems to fail when I try to implement it in an HTML file. Despite my efforts, I am unable to pinpoint the source of the issue. If you'd like to view the working version, here is the Fiddle demo. Bel ...