温馨提示:本文翻译自stackoverflow.com,查看原文请点击:dom - Chrome extension adding external javascript to current page's html
dom google-analytics google-chrome-extension javascript content-script

dom - Chrome扩展程序将外部JavaScript添加到当前页面的html中

发布于 2020-04-18 12:27:54

我通过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);
})();

查看更多

提问者
Vish
被浏览
65
2017-05-23 19:33

内容脚本不在页面范围内运行(另请参见),它们在扩展程序和网页之间的上下文中运行。

由于跟踪器的类型为“注入脚本”,因此这些跟踪器将完全在网页的上下文中运行。但是_gaqHasync变量没有。结果,跟踪脚本无法读取配置变量。

有两种(三种)修复方法。

  1. 使用此方法注入您的代码(如问题中所述)使用你的目的这种方法气馁,因为你的脚本将覆盖常用的全局变量。使用此方法实现脚本将破坏许多网站上的跟踪- 请勿使用它
  2. 在内容脚本的范围内完全运行代码:
    两个选项:
    1. 在扩展名中包含外部文件
    2. 在扩展名中包括外部文件,并实现自动更新功能。

方法1:完全本地副本

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

方法2:注入最新的GA

如果您想拥有最新版本的GA,则必须使用复杂的代码注入方式,因为无法从外部URL包含 Content脚本

这个答案的旧版本依赖于背景页面并chrome.tabs.executeScript用于此目的,但是自Chrome 20起,出现了更好的方法:使用chrome.storageAPI缓存JavaScript代码。为了使代码保持更新,我将在存储中存储一个“最后更新”的时间戳。您也可以改用chrome.alarmsAPI。

注意:如果用户没有互联网连接等,请不要在扩展名中包括外部文件的本地副本。 如果没有互联网连接,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