【问题标题】:Greasemonkey Userscript Blocked by Content Security PolicyGreasemonkey 用户脚本被内容安全策略阻止
【发布时间】:2020-12-16 22:41:17
【问题描述】:

以下 GreaseMonkey/ViolentMonkey/Tampermonkey 用户脚本在 Gmail 徽标旁边添加了一个 CLICK 锚点。

// ==UserScript==
// @name        CSP test 
// @namespace   Violentmonkey Scripts
// @match        *://mail.google.com/*
// @grant       none
// ==/UserScript==
 
function addAnchor(){
  let myanchor =  document.createElement("A");
  myanchor.appendChild(document.createTextNode("CLICK"));
  myanchor.setAttribute("href", "javascript:sampleFunc(this)"); 
  document.querySelectorAll('div[class="gb_xc gb_Ce"]')[1].appendChild(myanchor);
}
 
function sampleFunc(elt){ alert("Just an alert"); }
 
setTimeout(addAnchor, 4000);

理论上,点击应该会导致提示信息;在实践中,从浏览器控制台,警报被阻止:

内容安全政策:页面设置阻止了内联资源(“script-src”)的加载。

我已使用 Firefox 79 和 ViolentMonkey 2.12.7 运行用户脚本。

【问题讨论】:

  • 将 Violentmonkey 高级设置中的 Default injection mode 设置为 auto。另外,考虑使用 addEventListener 添加一个 js 监听器。
  • @wOxxOm:谢谢,addEventListener 有帮助。 //@inject-into auto 没有。出于安全原因,它还值得使用吗?

标签: javascript greasemonkey tampermonkey


【解决方案1】:

根据 wOxxOm 的建议,添加点击事件监听器(而不是 JavaScript 链接)是可行的:

// ==UserScript==
// @name        CSP test 
// @namespace   Violentmonkey Scripts
// @match        *://mail.google.com/*
// @grant       none
// ==/UserScript==
 
function addAnchor(){
  let myanchor =  document.createElement("A");
  myanchor.appendChild(document.createTextNode("CLICK"));
  myanchor.setAttribute("href", "#"); 
  myanchor.addEventListener("click", sampleFunc);
  document.querySelectorAll('div[class="gb_xc gb_Ce"]')[1].appendChild(myanchor);
}
 
function sampleFunc(elt){ alert("Just an alert"); }
 
setTimeout(addAnchor, 4000);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-30
    • 2021-08-12
    • 1970-01-01
    • 2021-08-21
    • 2021-09-19
    • 1970-01-01
    • 2017-09-30
    • 1970-01-01
    相关资源
    最近更新 更多