Greasemonkey Userscript Blocked by Content Security Policy

2.8k views Asked by At

The following GreaseMonkey/ViolentMonkey/Tampermonkey userscript adds a CLICK anchor next to the Gmail logo.

// ==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);

In theory, clicking should cause an alert message; in practice, as from the browser console, the alert is blocked by:

Content Security Policy: The page's settings blocked the loading of a resource at inline ("script-src").

I have run the userscript with Firefox 79 and ViolentMonkey 2.12.7.

1

There are 1 answers

0
antonio On

As suggested by wOxxOm, adding a click event listener (rather than a JavaScript link) works:

// ==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);