【发布时间】:2015-03-31 15:20:50
【问题描述】:
通常我使用以下代码sn-p,这个通常可以工作:
(function () {
function main() {
//...script body...
}
var OGloboCSS = { // var could be named anything, appropriate to the page
addJQuery: function (callback) {
var script = document.createElement("script");
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js");
script.addEventListener('load', function () {
var script = document.createElement("script");
script.textContent = "window.jQ=jQuery.noConflict(true);(" + callback.toString() + ")();";
document.body.appendChild(script);
}, false);
document.body.appendChild(script);
}
};
OGloboCSS.addJQuery(main);
})();
但偶尔我会在https://steamcommunity.com 上收到类似这样的错误:
拒绝加载脚本 'https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js' 因为它违反了以下内容安全政策指令: “script-src 'unsafe-eval' 'self' 'unsafe-inline' 'unsafe-eval' https://steamcommunity-a.akamaihd.net/https://api.steampowered.com/ http://www.google-analytics.comhttps://ssl.google-analytics.com https://www.google.comhttps://www.gstatic.com https://apis.google.com"。
解决方案基本上是,你必须改用 TamperMonkey 的 @require 标头指令,如下所示:
// @require https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js
// ==/UserScript==
window.jQ = $;
(function () {
/*this used to be: function main() */
//...same script body, without container function...
})();
这工作得很好,但它不能安全地将 jQuery 加载到jQ 变量,它破坏了$。真的有问题吗?是的,您可以从 steamcommunity.com 的讨论线程中的分页中断中看到这一点。
有什么方法可以@require jQ= 然后@grant jQ - 在 Tampermonkey 脚本和控制台中仍然给我jQ,不会破坏页内变量?
【问题讨论】:
-
您可以使用 tampermonkey 调度外部脚本,并在该外部脚本中在顶部使用无冲突 JQ 或加载 amd。
标签: javascript jquery google-chrome tampermonkey