2016-12-11 39 views
1

我能夠在本地HTML文件來執行以下的Greasemonkey:如何跨協議/計劃執行JavaScript文件?

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

我能夠執行在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); 

不過,我是不是能夠執行以下。 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中設置爲true。
我該如何在腳本標記中執行本地腳本文件?

+0

如果您向最後一個樣本添加了// @include file:/// C:/ fx/test/a.html',該怎麼辦? – LGSon

+0

您正試圖跨域訪問文件系統。它在大多數瀏覽器中都是不允許的。 – Bindrid

+0

'fileIsGreaseable'只是意味着即使您在瀏覽器中訪問'file://'url(通常它只攔截「http://」和「https://」),greasemonkey也會運行腳本。 – melpomene

回答

0

嘗試跨這些協議加載資源是一個基本的安全錯誤。嘗試想象惡意網站(或其第三方廣告)可能(並且確實)加載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)協議訪問您的資源。