Search code examples
javascriptgreasemonkey

How to execute a javascript file across protocols/schemes?


I was able to execute the following Greasemonkey in local HTML file:

// ==UserScript==
// @name        test
// @include     file:///C:/fx/test/a.html
// @grant       none
// ==/UserScript==

var scriptElement = document.createElement( "script" );
scriptElement.type = "text/javascript";
scriptElement.src = "file://c:/fx/alert.js";
document.head.appendChild( scriptElement );

I was able to execute the following in localhost:

// ==UserScript==
// @name        testWeb
// @include     http://localhost/test/a.html
// @grant       none
// ==/UserScript==

var scriptElement = document.createElement( "script" );
scriptElement.type = "text/javascript";
scriptElement.src = "http://localhost/test/alert.js";
document.head.appendChild( scriptElement );

However, I was not able to execute the following. There is HTML file in web server and there is script file in local drive.

// ==UserScript==
// @name        testWeb
// @include     http://localhost/test/a.html
// @grant       none
// ==/UserScript==

var scriptElement = document.createElement( "script" );
scriptElement.type = "text/javascript";
scriptElement.src = "file://c:/fx/alert.js";
document.head.appendChild( scriptElement );

greasemonkey.fileIsGreaseable was set to true in about:config.
What should I do to execute a local script file in script tag?


Solution

  • It is a basic security error to try and load resources across protocols like that. Try to imagine the unspeakable evil a malicious website (or its 3rd party ad) could (and did) do if it could just load file:// resources.

    For this reason, the browser will block such attempts across protocols with messages like:

    Security Error: Content at http://evil.com/pwner.htm may not load or link to file:///C:/user_passwords.db

    (Firefox)


    You already know what you have to do:

    • When the script runs against a file:// protocol page, access your resource with the file:// protocol.
    • When the script runs against an http(s) protocol page, access your resource with the http(s) protocol.