Greasemonkey用户脚本被内容安全策略禁止

问题描述

以下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运行了用户脚本。

解决方法

按照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);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...