如何使用谷歌图表并设置document.domain

时间:2013-08-22 22:54:25

标签: javascript iframe google-visualization

似乎更改document.domain属性会导致Google Charts无法在Internet Explorer中工作(至少版本8)。下面是一个非常简单的页面,演示了这个问题。示例代码几乎直接来自Google Charts库沙箱。唯一的主要区别是我添加了一个先前的JavaScript来设置document.domain。

我们正在开发子域名,比如说“test.example.com”,出于其他原因,我们需要将document.domain属性设置为“example.com”。这打破了图表。它只是说“你的浏览器不支持图表。”

即使您将document.domain设置为“test.example.com”(默认情况下也是如此),图表仍然无效。据我所知,谷歌图表正在IE8中创建一个iframe,并通过更改document.domain来触发同源安全策略。

因为我无法控制Google库,所以我无法在iframe上设置document.domain(因为我现在无权从上层页面访问它,我有JavaScript)。有关如何解决此问题的任何想法,同时仍然保持更改document.domain的能力?

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript">
        document.domain = "example.com";
    </script>
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript">
      google.load("visualization", "1", {packages:["corechart"]});
      google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable([
          ['Year', 'Sales', 'Expenses'],
          ['2004',  1000,      400],
          ['2005',  1170,      460],
          ['2006',  660,       1120],
          ['2007',  1030,      540]
        ]);

        var options = {
          title: 'Company Performance',
          hAxis: {title: 'Year', titleTextStyle: {color: 'red'}}
        };

        var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="chart_div" style="width: 900px; height: 500px;"></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

仍然没有根本原因的解决方案。但我们最终做的只是推迟了document.domain属性的设置,直到Google图表在页面上呈现为止。然后,您可以设置document.domain而不会导致问题。

显然,如果你动态地从页面添加/删除图表,这不会起作用,但对于绝大多数情况应该如此。