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

How can I design DIVs to resemble a radio station or television schedule grid?

Check out the JSFiddle for my page with the source code included: https://jsfiddle.net/g0kw1Le8/ Here is a snippet of the source code: <TITLE>Hallam FM - Best Variety of Hits</TITLE> <style> /* CSS styles go here */ /* End of CSS */ & ...

JavaScript for validating dimension text input has unique functionalities

I am looking for guidance on validating an ASP textbox using JavaScript. My goal is to validate a user's input in the format of 4-1/2, 80-1/2, 6/8, or simply 5. Only these types of patterns should be allowed, and each input must contain only one numbe ...

Having difficulty passing a function as a parameter from a NextJS component

I have a code snippet like this in a NextJS component: const [currentGPS, setCurrentGPS] = useState({coords:{latitude:0.0,longitude:0.0}}) useEffect(() => { utl.getGPSLocation( (v:{coords: {latitude:number; longitude:n ...

CSS files not loading on live-server

My HTML file is linked to a CSS file, but the CSS doesn't seem to load when I use live-server. Interestingly, the CSS works perfectly fine when I directly open the HTML file in a browser. The CSS file is located outside the directory where my HTML fi ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

What is the correct way to utilize the Vuex mutation payload object effectively?

I have two input fields where I can enter a value to search for either the name of a company or the location. The search functionality works when only one argument is provided in the foundJobs mutation and action. However, when the payload contains an obje ...

Substitute "Basic Authentication" with "Form Authentication"

Is there a way in W20 to switch from using "Basic Authentication" to "Form Authentication"? The current documentation mentions only the use of "basicAuth" and does not provide information on implementing form authentication. Our app is built with Angular ...

React array mapping issue does not produce any error message

I have exhaustively searched through every answer on Stack Overflow in hopes of finding a solution to my problem. However, I find myself at an impasse as there are no error messages appearing in the console. It seems that there is a hidden bug eluding my d ...

Creating a dynamic onclick function that depends on a variable passed from a while loop in PHP

If you're familiar with PHP, I have a scenario for you. Let's say there's a list of items generated using a while loop in PHP. Each item has a sub-list that should only appear when clicked on. I tried using the onclick function in jQuery but ...

How can I conceal login and register router-links in the Vue + Laravel SPA project navbar immediately after a user logs in?

Currently, I am working on my Bachelor's degree project and have encountered a specific issue. While the login, register, and logout functions all seem to be working well, there is an inconsistency with the navigation bar not automatically switching b ...

Create-react-app fails to generate a template even though the react framework is fully updated

I attempted to set up a fresh react directory using npx create-react-app. Unfortunately, every solution I tried resulted in the template not being provided, with the common suggestion being that my version of create-react-app may be outdated. I verified t ...

Twitter Bootstrap Dropdown PHP link fails to function

Recently, I designed a dropdown menu to be used on a PHP page. The main button, which contains the dropdown links, needs to still function as a link to another page. Despite following all the instructions provided on the Bootstrap website, the main button ...

The button in Bootstrap 4 that triggers the modal stays in a highlighted or clicked state even after the modal has been

I am currently utilizing the button below to trigger the opening of a modal window However, upon closing the modal, it seems to maintain a highlighted or clicked appearance with a shadow effect. Initially, I assumed I could address this issue by implement ...

Ways to pause JavaScript execution until a function completes its task

Is it possible to pause JavaScript execution until a specific function finishes in JavaScript/NodeJS? For instance: https://i.stack.imgur.com/Ta8pj.png Imagine the first line of code triggers an alert, and JavaScript stops executing until the user interac ...

Prevent selection duplication in adjacent select by disabling the option in AngularJS ng-options

In my table, I have 2 select options that change dynamically. <tr> <th>Start time</th> <th>End time</th> </tr> <tr ng-repeat="s in config.time"> <td> <select ng-model="s.start_time" ...

The process of binding two variables in the same select element

Here is the code snippet that I am working with: <div class="form-group "> <label for="field_type"><b>Type</b></label> <div class="input-icon right"> <select required class="form-control" ...

What is the best way to update the color of an fa icon when an error message is displayed using PHP

I am facing an issue with my form where error messages are displayed on certain input fields. The error messages show up correctly, but I want to change the color of the "fa" icon in the field when its corresponding error message appears. My goal is to ma ...

Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status. My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId. I have two specifi ...

Only one ID is recognized by jQuery

I have a group of three checkboxes set up like this: <input id="image_tagging" class="1" type="checkbox" value="1" checked="checked" name="data[image_tagging]"> Now, I've created an AJAX function (which is functioning correctly), but it seems ...

Ensuring divs are centered when resizing the page

Is there a way to center an unordered list of tables while ensuring that it remains centered even when the window is resized? The list should move each table to a new line if they can no longer fit. Check out the code snippet below for reference: <d ...