本文介绍了Chrome扩展程序将外部JavaScript添加到当前页面的html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我通过Chrome扩展程序将一些外部JavaScript添加到页面末尾。然后,外部JavaScript尝试将一些数据发回服务器,但这并不会发生。 JavaScript想要获取当前页面和引荐来源的URL并将其发回服务器。 任何人都可以告诉我这里有什么问题,如何不能这样我可以从当前页面发布数据 manifest.json {名称:网站安全,版本:1.0,manifest_version:2,描述:网站安全扩展 $ bbrowser_action:{name:查看网站信息,default_icon:icon.png,default_popup:popup.html },权限:[tabs,http:// * / *,https:// * / *],background:{ //scripts:[refresh.js] page:background.html},content_security_policy :script-srcself 'https://ssl.google-analytics.com; object-src'self', //background_page:background.html content_scripts:[ {matches:[ < all_urls>],js:[contentScript.js] } ] } / pre> 现在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 变量不会。因此,跟踪脚本无法读取配置变量。 有两种(三种)修复方法。 使用此方法。为了您的目的使用此方法不鼓励,因为您的脚本会覆盖常用的全局变量。使用这种方法实现你的脚本将会在很多网站上中断跟踪 - 不要使用它。 完全运行代码内容脚本的范围: 两个选项: 在扩展名中包含外部文件 在扩展名中包含外部文件,并实现自动更新功能。 方法1:完全本地复制 manifest.json (只有相关部分显示): {name:网站安全,版本:1.0,manifest_version:2,description:网站安全扩展,权限:[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 中包含。 此答案的旧版本依赖于背景页面和 chrome.tabs.executeScript 为此目的,但由于Chrome 20可以使用更好的方法:使用 chrome.storage 缓存JavaScript代码的API。 为了保持代码更新,我将在存储中存储最后更新的时间戳记;您还可以使用 chrome.alarms API。 注意:不要忘记在扩展程序中包含外部文件的本地副本,以防用户没有互联网连接等。 没有互联网连接,Google Analytics(分析)将无法正常工作。 内容脚本 activate-ga.js 。 var UPDATE_INTERVAL = 2 * 60 * 60 * 1000; // 2小时后更新 //从存储空间检索GA chrome.storage.local.get({ lastUpdated:0, code:''},function(items){ if(Date.now() - items.lastUpdated> UPDATE_INTERVAL){ //获取更新的文件,如果找到,保存 get('https://ssl.google-analytics.com/ga.js',function(code){ if(!code)return; chrome.storage.local.set({最后更新:Date.now(),code:code}); }); } if(items.code)//缓存的GA可用,使用执行(items.code); else //尚未缓存版本从扩展名加载 get(chrome.extension.getURL('ga.js'),execute); }); //通常在几毫秒内运行函数execute(code){ try {window.eval(code); catch(e){console.error(e); } //运行其余的代码。 //如果您的扩展名依赖于GA,请从此初始化。 // ... } 函数get(url,callback){ var x = new XMLHttpRequest(); x.onload = x.onerror = function(){callback(x.responseText); }; x.open('GET',url); x.send(); } 最低清单文件: name:网站安全,version:1.0,manifest_version:2,permission:[tabs,http:// * / *,https:// * / *],content_scripts b $ b {匹配:[< all_urls>],js:[activate-ga.js] } ],web_accessible_resources:[ga.js] } 方法可用于其他跟踪器。最低许可要求: https://ssl.google-analytics.com/ga。 js ,所以应该在权限部分添加。 https:// * / * 或< all_urls> 也足够了。 可选: unlimitedStorage - 如果要存储大量的 chrome.storage 。 I am adding some external JavaScript to the end of the page via my chrome extension. The external JavaScript then tries to post some data back to the server, however that is not taking place.The JavaScript wants to get the url of the current page and the referrer and post it back to the server.Can anyone please advice me what is wrong here and how can I if not possible this way can I post data from the current page back to the server.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"] } ]}for now contentScript.jsvar _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);})(); 解决方案 Content scripts do not run in the scope of the page (see also), they run in a context between your extension and the web page.Since the trackers are of the type "Injected script", these fully run in the context of the web page. But the _gaq and Hasync variables don't. As a result, the track scripts cannot read the configuration variables.There are two (three) ways to fix it.Inject your code (as posted in the question) using this method. Using this method for your purpose is discouraged, because your script overwrites a commonly used global variable. Implementing your script using this method will break the tracking on many websites - do not use it.Fully run the code within the scope of a content script:Two options:Include the external files in the extensionInclude the external files in the extension, plus implement an auto-update feature.Method 1: Fully local copymanifest.json (only the relevant parts are shown):{ "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"] } ]}In ga-config.js, define the variables as follows: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', '']);Download https://ssl.google-analytics.com/ga.js, and save it as ga.js.Download http://s10.histats.com/js15_as.js, and save it as js15_as.js.Method 2: Injecting a Up-to-date GAIf you want to have an up-to-date version of GA, a convoluted way of injecting the code has to be used, because Content scripts cannot be included from an external URL.An old version of this answer relied on the background page and chrome.tabs.executeScript for this purpose, but since Chrome 20, a better method has become available: Use the chrome.storage API to cache the JavaScript code.To keep the code updated, I will store a "last updated" timestamp in the storage; you can also use the chrome.alarms API instead.Note: Do not forget to include a local copy of the external file in your extension, in case the user does not have an internet connection, etc. Without an internet connection, Google Analytics wouldn't work anyway.Content script, activate-ga.js.var UPDATE_INTERVAL = 2 * 60 * 60 * 1000; // Update after 2 hour// Retrieve GA from storagechrome.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 millisecondsfunction 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();}Minimum manifest file:{ "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"]}The same method can be used for other trackers. The minimum permission requirements:https://ssl.google-analytics.com/ga.js, so that should be added at the permissions section. https://*/* or <all_urls> is also sufficient.optional: unlimitedStorage - If you want to store a large piece of data with chrome.storage. 这篇关于Chrome扩展程序将外部JavaScript添加到当前页面的html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 09-27 01:33