我通过chrome扩展程序在页面末尾添加了一些外部JavaScript。然后,外部JavaScript尝试将一些数据发布回服务器,但是这并没有发生。
JavaScript希望获取当前页面和引荐来源网址的网址,然后将其发布回服务器。
任何人都可以请我告诉我这里出了什么问题,怎么办呢?如果不能的话,如何将当前页面中的数据发布回服务器。
manifest.json
{
"name": "Website Safety",
"version": "1.0",
"manifest_version": 2,
"description": "The Website Safety Extension.",
"browser_action": {
"name": "View the website information for ",
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"background": {
// "scripts": ["refresh.js"]
"page": "background.html"
},
"content_security_policy": "script-src 'self' https://ssl.google-analytics.com; object-src 'self'",
//"background_page": "background.html"
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["contentScript.js"]
}
]
}
现在为contentScript.js
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31046309-1']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
//ga.src = 'https://ssl.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
var _Hasync= _Hasync|| [];
_Hasync.push(['Histats.start', '1,1342541,4,0,0,0,00000000']);
_Hasync.push(['Histats.fasi', '1']);
_Hasync.push(['Histats.track_hits', '']);
(function() {
var hs = document.createElement('script'); hs.type = 'text/javascript'; hs.async = true;
hs.src = ('http://s10.histats.com/js15_as.js');
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(hs);
})();
内容脚本不在页面范围内运行(另请参见),它们在扩展程序和网页之间的上下文中运行。
由于跟踪器的类型为“注入脚本”,因此这些跟踪器将完全在网页的上下文中运行。但是_gaq
和Hasync
变量没有。结果,跟踪脚本无法读取配置变量。
有两种(三种)修复方法。
manifest.json
(仅显示相关部分):
{
"name": "Website Safety",
"version": "1.0",
"manifest_version": 2,
"description": "The Website Safety Extension.",
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["ga-config.js", "ga.js", "js15_as.js"]
}
]
}
在中ga-config.js
,定义变量如下:
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-31046309-1']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_trackPageview']);
var _Hasync= _Hasync|| [];
_Hasync.push(['Histats.start', '1,1342541,4,0,0,0,00000000']);
_Hasync.push(['Histats.fasi', '1']);
_Hasync.push(['Histats.track_hits', '']);
下载https://ssl.google-analytics.com/ga.js,并将其另存为ga.js
。
下载http://s10.histats.com/js15_as.js,并将其另存为js15_as.js
。
如果您想拥有最新版本的GA,则必须使用复杂的代码注入方式,因为无法从外部URL包含 Content脚本。
这个答案的旧版本依赖于背景页面并chrome.tabs.executeScript
用于此目的,但是自Chrome 20起,出现了更好的方法:使用chrome.storage
API缓存JavaScript代码。为了使代码保持更新,我将在存储中存储一个“最后更新”的时间戳。您也可以改用chrome.alarms
API。
注意:如果用户没有互联网连接等,请不要在扩展名中包括外部文件的本地副本。 如果没有互联网连接,Google Analytics(分析)将无法正常工作。
内容脚本,activate-ga.js
。
var UPDATE_INTERVAL = 2 * 60 * 60 * 1000; // Update after 2 hour
// Retrieve GA from storage
chrome.storage.local.get({
lastUpdated: 0,
code: ''
}, function(items) {
if (Date.now() - items.lastUpdated > UPDATE_INTERVAL) {
// Get updated file, and if found, save it.
get('https://ssl.google-analytics.com/ga.js', function(code) {
if (!code) return;
chrome.storage.local.set({lastUpdated: Date.now(), code: code});
});
}
if (items.code) // Cached GA is available, use it
execute(items.code);
else // No cached version yet. Load from extension
get(chrome.extension.getURL('ga.js'), execute);
});
// Typically run within a few milliseconds
function execute(code) {
try { window.eval(code); } catch (e) { console.error(e); }
// Run the rest of your code.
// If your extension depends on GA, initialize it from here.
// ...
}
function get(url, callback) {
var x = new XMLHttpRequest();
x.onload = x.onerror = function() { callback(x.responseText); };
x.open('GET', url);
x.send();
}
最小清单文件:
{
"name": "Website Safety",
"version": "1.0",
"manifest_version": 2,
"permissions": [
"tabs", "http://*/*", "https://*/*"
],
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["activate-ga.js"]
}
],
"web_accessible_resources": ["ga.js"]
}
相同的方法可用于其他跟踪器。最低权限要求:
https://ssl.google-analytics.com/ga.js
,因此应将其添加到“权限”部分。https://*/*
还是<all_urls>
足够的。unlimitedStorage
-如果要使用来存储大量数据chrome.storage
。
抱歉,我不得不对此表示反对,因为建议的方法将他锁定在ga.js的静态版本中。它阻止他获取更新,因此,此更新应由Google提供。请参阅官方建议:support.google.com/googleanalytics/bin/…
@galambalazs更新了我的答案以包括该功能。
嗨,听起来不错,但我面临的问题是它仍然无法跟踪用户正在浏览的页面。它无法将任何数据发布回Google的服务器。您能帮我弄清楚我做错了什么吗?我用了你给我的代码。顺便说一句,感谢您帮助我提高对这一主题的了解,尽管从Google的文档中似乎很容易理解,但我并不是真的那样。我对此表示赞同,将做一些尝试来修复我可能出错的地方。
一切正常,但是奇怪的是,谷歌分析没有跟踪用户访问了哪些网站以及有关用户在网络上的访问位置的其他数据。另外,是否有办法知道用户何时打开/关闭选项卡或窗口?
@ user658911将事件监听器绑定到
chrome.tabs.onRemoved
。关于跟踪:我的演示效果很好。您是否还有其他将事件侦听器绑定到的后台脚本chrome.extension.onRequest
?