0

我想获取位于同一域中外部页面的元素的背景颜色。我有一个可行的解决方案优先方法,但必须有更好的方法,我希望你能指出我正确的方向。

我的方法

我决定首先将外部页面加载到 iframe 中:

var $page = $('<iframe/>').attr('src', 'http://mydomain.com/page');

然后将 iFrame 附加到我的当前页面:

$('#iframe-placeholder').append($page);

最后我访问 CSS 属性:

$('iframe').load(function(){
  var backgroundColor = $(this).contents().find('#my-element').css('backgroundColor');
});

这种方法的缺点

  1. 很慢
  2. 它是异步的
  3. 它实际上不起作用。总是返回transparent

问题

有没有办法获取该外部页面的 CSS 属性?
我真的需要同步调用并将整个页面加载到 iFrame 中(如果这是一个解决方案)只是一种矫枉过正。

任何建议将不胜感激......

4

2 回答 2

0

您是否尝试过异步加载页面内容并从那里开始工作?

var backgroundColor;
$.ajax({
    type: 'GET',
    url: 'http://mydomain.com/page',
    dataType: 'html',
    success: function(pageData) {
        var page = $(pageData);
        backgroundColor = page.find('#my-element').css('backgroundColor');
    }
});

请注意,这是未经测试的代码。

于 2013-08-19T17:49:12.713 回答
0

好的,我理解使用 iframe 加载要避免的东西的诱惑same origin policy,但我想提请您注意其他事情:CORS

考虑这种情况,网站 alice.com 有一些网站 bob.com 想要访问的数据。通过支持 CORS 请求,alice.com 可以添加一些特殊的响应标头,允许 bob.com 访问数据。

端到端示例:

// Create the XHR object.
function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

// Helper method to parse the title tag from the response.
function getTitle(text) {
  return text.match('<title>(.*)?</title>')[1];
}

// Make the actual CORS request.
function makeCorsRequest() {
  // All HTML5 Rocks properties support CORS.
  var url = 'http://updates.html5rocks.com';

  var xhr = createCORSRequest('GET', url);
  if (!xhr) {
    alert('CORS not supported');
    return;
  }

  // Response handlers.
  xhr.onload = function() {
    var text = xhr.responseText;
    var title = getTitle(text);
    alert('Response from CORS request to ' + url + ': ' + title);
  };

  xhr.onerror = function() {
    alert('Woops, there was an error making the request.');
  };

  xhr.send();
}

运行示例并在浏览器的调试器中观察网络请求,以查看发出的实际请求。

此外,您可以访问我提到的网站,以全面了解该方法的工作原理。

于 2013-08-19T17:55:01.513 回答