我正在尝试使用 google 为我的 rails 应用程序提供的 javascript 代码实现 google analytics embed api,并从此链接获取帮助 -> https://ga-dev-tools.appspot.com/embed-api/。现在我不知道如何在每次页面更改时运行这些脚本,因为这些 javascripts 侦听页面加载事件,并且 rails 使用实际上不加载页面的 turbolinks 它只交换正文和标题。现在的问题是 javascript 没有响应,因为它不知道该页面已被更改。请帮帮我。
<script>
(function (w, d, s, g, js, fs) {
g = w.gapi || (w.gapi = {}); g.analytics = { q: [], ready: function (f) { this.q.push(f); } };
js = d.createElement(s); fs = d.getElementsByTagName(s)[0];
js.src = 'https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js, fs); js.onload = function () { g.load('analytics'); };
}(window, document, 'script'));
</script>
<div id="embed-api-auth-container"></div>
<div id="chart-container"></div>
<div id="view-selector-container"></div>
<script>
gapi.analytics.ready(function () {
/**
* Authorize the user immediately if the user has already granted access.
* If no access has been created, render an authorize button inside the
* element with the ID "embed-api-auth-container".
*/
gapi.analytics.auth.authorize({
container: 'embed-api-auth-container',
clientid: '7xxxxxxxxxx-mtgoounogp8pu2brjsi1mfpbrohtcppd.apps.googleusercontent.com'
});
/**
* Create a new ViewSelector instance to be rendered inside of an
* element with the id "view-selector-container".
*/
var viewSelector = new gapi.analytics.ViewSelector({
container: 'view-selector-container'
});
// Render the view selector to the page.
viewSelector.execute();
/**
* Create a new DataChart instance with the given query parameters
* and Google chart options. It will be rendered inside an element
* with the id "chart-container".
*/
var dataChart = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
metrics: 'ga:sessions',
dimensions: 'ga:date',
'start-date': '30daysAgo',
'end-date': 'yesterday'
},
chart: {
container: 'chart-container',
type: 'LINE',
options: {
width: '100%'
}
}
});
/**
* Render the dataChart on the page whenever a new view is selected.
*/
viewSelector.on('change', function (ids) {
dataChart.set({ query: { ids: ids } }).execute();
});
});
</script>
我的代码第一次正常运行,但是如果我切换到另一个链接或在通过 turbolinks 访问另一个页面后返回同一页面,则 javascript 不会运行。
请帮忙。谢谢