如何跨 protocols/schemes 执行 javascript 文件?

How to execute a javascript file across protocols/schemes?

我能够在本地 HTML 文件中执行以下 Greasemonkey:

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

我能够在本地主机中执行以下操作:

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

但是,我无法执行以下操作。 Web 服务器中有 HTML 文件,本地驱动器中有脚本文件。

// ==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 在 about:config 中设置为真。
在script标签中执行本地脚本文件应该怎么做?

像这样尝试跨协议加载资源是一个基本的安全错误。试想一下,如果恶意网站(或其第 3 方广告)可以(并且已经)加载 file:// 资源,那么它可以(并且已经)做出了难以形容的邪恶。

因此,浏览器将阻止此类跨协议的尝试,并显示如下消息:

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

(火狐)


你已经知道你要做什么了:

  • 当脚本针对 file:// 协议页面运行时,使用 file:// 协议访问您的资源。
  • 当脚本针对 http(s) 协议页面运行时,使用 http(s) 协议访问您的资源。