Search code examples
javascriptcontent-security-policytampermonkey

Tampermonkey script blocked by a CSP error


I am new to javascript and Tampermonkey. I wanted to add a frame to the Memrise's website. The code is as follows:

// ==UserScript==
// @name         Merise
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  try to take over the world!
// @author       k1
// @match        https://app.memrise.com/aprender/*
// @icon         https://www.google.com/s2/favicons?domain=memrise.com
// @grant        none
// ==/UserScript==

(function() {
    'use strict';
    var word = document.getElementsByClassName("sc-1nck79x-5 jPETsr")[0]
    var bdy = document.getElementsByClassName("sc-r1ec2z-1 evBYsl")[0]
    var defl = "https://learnersdictionary.com/definition/" + word.innerHTML
    var fr = document.createElement("IFRAME");
    fr.height = "500px"
    fr.src = defl
    fr.style.maxWidth="90%"
    bdy.appendChild(fr);
})();

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

Please let me know how can I fix this if there is any way to do that. Thanks.


Solution

  • Use GM_addElement to circumvent such CSP restrictions:

    // ==UserScript==
    // @name         Merise
    // @match        https://app.memrise.com/aprender/*
    // @grant        GM_addElement
    // ==/UserScript==
    
    var word = document.getElementsByClassName('sc-1nck79x-5 jPETsr')[0].textContent;
    var bdy = document.getElementsByClassName('sc-r1ec2z-1 evBYsl')[0];
    GM_addElement(bdy, 'iframe', {
      src: 'https://learnersdictionary.com/definition/' + encodeURIComponent(word),
      style: 'width: 90%; height: 500px;',
    });