Подтвердить что ты не робот

Доступ к таблице междоменного стиля с помощью .cssRules

Я получаю эту ошибку в Firebug, когда пытаюсь получить доступ к некоторым файлам CSS, размещенным на внешних доменах:

Security error" code: "1000
rules = styleSheets[i].cssRules;

Используемый мной код:

$(document).ready(function () {
    $("p").live('mousedown', function getCSSRules(element) {
        element = $(this);
        var styleSheets = document.styleSheets;
        var matchedRules = [],
            rules, rule;
        for (var i = 0; i < styleSheets.length; i++) {
            rules = styleSheets[i].cssRules;
            for (var j = 0; j < rules.length; j++) {
                rule = rules[j];
                if (element.is(rule.selectorText)) {
                    matchedRules.push(rule.selectorText);
                }
            }
        }
        alert(matchedRules);
    });
});

Есть ли способ исправить это, помимо перемещения всех файлов CSS в одном домене?

4b9b3361

Ответ 1

Единственное реальное решение этой проблемы - CORS загружает ваш CSS в первую очередь. Используя CORS XMLHttpRequest для загрузки CSS из внешнего домена, а затем введя responseText (на самом деле responseCSS в этом случае) на страницу через что-то вроде:

function loadCSSCors(stylesheet_uri) {
  var _xhr = global.XMLHttpRequest;
  var has_cred = false;
  try {has_cred = _xhr && ('withCredentials' in (new _xhr()));} catch(e) {}
  if (!has_cred) {
    console.error('CORS not supported');
    return;
  }
  var xhr = new _xhr();
  xhr.open('GET', stylesheet_uri);
  xhr.onload = function() {
    xhr.onload = xhr.onerror = null;
    if (xhr.status < 200 || xhr.status >= 300) {
      console.error('style failed to load: ' + stylesheet_uri);
    } else {
      var style_tag = document.createElement('style');
      style_tag.appendChild(document.createTextNode(xhr.responseText));
      document.head.appendChild(style_tag);
    }
  };
  xhr.onerror = function() {
      xhr.onload = xhr.onerror = null;
      console.error('XHR CORS CSS fail:' + styleURI);
  };
  xhr.send();
}

Таким образом, CSS файлы будут интерпретироваться браузером как исходящие из того же исходного домена, что и ответ главной страницы, и теперь у вас будет доступ к свойствам cssRules ваших таблиц стилей.

Ответ 2

С 2013 года вы можете установить атрибут "crossorigin" в <link> -Element, чтобы сообщить браузеру, что этот CSS доверен (Mozilla, W3). Для этого сервер, на котором размещен CSS, должен установить заголовок Access-Control-Allow-Origin: *.

После этого вы можете получить доступ к своим правилам через Javascript.

Ответ 4

Я написал небольшую функцию, которая позволит решить проблему с загрузкой кросс-браузера, включая FF. Комментарии к GitHub помогают объяснить использование. Полный код на https://github.com/srolfe26/getXDomainCSS.

Отказ от ответственности: Код ниже зависит от jQuery.

Иногда, если вы вытаскиваете CSS из того места, где вы не можете контролировать настройки CORS, которые вы можете получить до CSS с тегом <link>, основная проблема, которая будет решена, становится зная, когда ваш призыв CSS загружен и готов к использованию. В более старом IE вы можете запускать прослушиватель on_load при загрузке CSS.

Более новые браузеры, похоже, требуют старомодного опроса, чтобы определить, когда файл загружен, и при определении загрузки нагрузки возникают проблемы с несколькими браузерами. См. Код ниже, чтобы поймать некоторые из этих причуд.

/**
 * Retrieves CSS files from a cross-domain source via javascript. Provides a jQuery implemented
 * promise object that can be used for callbacks for when the CSS is actually completely loaded.
 * The 'onload' function works for IE, while the 'style/cssRules' version works everywhere else
 * and accounts for differences per-browser.
 *
 * @param   {String}    url     The url/uri for the CSS file to request
 * 
 * @returns {Object}    A jQuery Deferred object that can be used for 
 */
function getXDomainCSS(url) {
    var link,
        style,
        interval,
        timeout = 60000,                        // 1 minute seems like a good timeout
        counter = 0,                            // Used to compare try time against timeout
        step = 30,                              // Amount of wait time on each load check
        docStyles = document.styleSheets        // local reference
        ssCount = docStyles.length,             // Initial stylesheet count
        promise = $.Deferred();

    // IE 8 & 9 it is best to use 'onload'. style[0].sheet.cssRules has problems.
    if (navigator.appVersion.indexOf("MSIE") != -1) {
        link = document.createElement('link');
        link.type = "text/css";
        link.rel = "stylesheet";
        link.href = url;

        link.onload = function () {
            promise.resolve();
        }

        document.getElementsByTagName('head')[0].appendChild(link);
    }

    // Support for FF, Chrome, Safari, and Opera
    else {
        style = $('<style>')
            .text('@import "' + url + '"')
            .attr({
                 // Adding this attribute allows the file to still be identified as an external
                 // resource in developer tools.
                 'data-uri': url
            })
            .appendTo('body');

        // This setInterval will detect when style rules for our stylesheet have loaded.
        interval = setInterval(function() {
            try {
                // This will fail in Firefox (and kick us to the catch statement) if there are no 
                // style rules.
                style[0].sheet.cssRules;

                // The above statement will succeed in Chrome even if the file isn't loaded yet
                // but Chrome won't increment the styleSheet length until the file is loaded.
                if(ssCount === docStyles.length) {
                    throw(url + ' not loaded yet');
                }
                else {
                    var loaded = false,
                        href,
                        n;

                    // If there are multiple files being loaded at once, we need to make sure that 
                    // the new file is this file
                    for (n = docStyles.length - 1; n >= 0; n--) {
                        href = docStyles[n].cssRules[0].href;

                        if (typeof href != 'undefined' && href === url) {
                            // If there is an HTTP error there is no way to consistently
                            // know it and handle it. The file is considered 'loaded', but
                            // the console should will the HTTP error.
                            loaded = true;
                            break;
                        }
                    }

                    if (loaded === false) {
                        throw(url + ' not loaded yet');
                    }
                }

                // If an error wasn't thrown by this point in execution, the stylesheet is loaded, proceed.
                promise.resolve();
                clearInterval(interval);
            } catch (e) {
                counter += step;

                if (counter > timeout) {
                    // Time out so that the interval doesn't run indefinitely.
                    clearInterval(interval);
                    promise.reject();
                }

            }
        }, step);   
    }

    return promise;
}

Ответ 5

Если это срабатывает для вас, потому что некоторые из ваших CSS могут появляться из других источников, но НЕ бит, который вас интересует, используйте блок try... catch следующим образом:

function cssAttributeGet(selectorText,attribute) {
  var styleSheet, rules, i, ii;
  selectorText=selectorText.toLowerCase();
  if (!document.styleSheets) {
    return false;
  }
  for (i=0; i<document.styleSheets.length; i++) {
    try{
      styleSheet=document.styleSheets[i];
      rules = (styleSheet.cssRules ? styleSheet.cssRules : styleSheet.rules);
      for (ii=0; ii<rules.length; ii++) {
        if (
          rules[ii] && rules[ii].selectorText &&
          rules[ii].selectorText.toLowerCase()===selectorText &&
          rules[ii].style[attribute]
        ){
          return (rules[ii].style[attribute]);
        }
      }
    }
    catch(e){
      // Do nothing!
    };
  }
  return false;
}

Ответ 6

У меня была аналогичная проблема под firefox и chrome. Я решил это жестким способом, добавив в мой домен файл css, который включал в себя код cs для домена, например:

<style type="text/css">
@import url("https://externaldomain.com/includes/styles/cookie-btn.css");
</style>

Это быстро, но грязно. Он рекомендовал хранить все файлы css в вашем домене.