Search code examples
tampermonkeyuserscripts

How to load an image using userscript from another domain when script is on github


I tried a few way to load an image into the page from my userscript, using tampermonkey.

The image needs to come from localhost where my nodejs is running then display in the web page. Github has some meta tag which prevents the loading of the image, I get the following in the console log.

In the general case, how can I load an image from localhost using tampermonkey and still work regardless of these meta tags?

Refused to load the image 'blob:https://github.com/2db84e5a-9884-4fec-a76d-f68726e9a89f'
 because it violates the following Content Security Policy directive: "img-src 'self'
 data: github.githubassets.com identicons.github.com github-cloud.s3.amazonaws.com 
secured-user-images.githubusercontent.com/ 
github-production-user-asset-6210df.s3.amazonaws.com 
customer-stories-feed.github.com spotlights-feed.github.com *.githubusercontent.com".

Thanks for response, the error message I show is due to me trying to use the binary of the image by js by requesting its data from my server on localhost, I had previously before this error also had same type of error when specify <img src="... where image comes from localhost.


Solution

  • The error you are seeing is due to GitHub's Content Security Policy.

    The only way to get around it is by bypassing it. Tampermonkey provides an API method for adding elements to the DOM, in the page scope, which is supposed to bypass page CSP.

    Using GM_addElement to add the image element should work well for you.

    GM_addElement(tag_name, attributes)
    GM_addElement(parent_node, tag_name, attributes)
    

    Example:

    GM_addElement('img', {
      src: 'https://example.com/image.png'
    });