2014-01-22 211 views
3

我想更改网页显示的部分,是否可以用userscript覆盖功能?如何使用脚本覆盖函数?

下面是我想重写的功能(也found Here):

function StartDrawing() { 
    if ((typeof (systemsJSON) != "undefined") && (systemsJSON != null)) { 
     var stellarSystemsLength = systemsJSON.length; 
     $('#mapDiv').empty(); 
     if (stellarSystemsLength > 0) { 
      InitializeRaphael(); 

      var i = 0; 
      for (i = 0; i < stellarSystemsLength; i++){ 
       var stellarSystem = systemsJSON[i]; 
       DrawSystem(stellarSystem) 
      } 
     } 
    } 
} 

这将让我跑我自己的绘图算法。

如何使用铬(或Firefox)中的userscript做到这一点?

+3

只需再次定义它 – exussum

回答

4

请参阅"Accessing Variables (and Functions) from Greasemonkey to Page & vice versa

Userscripts从目标页面分开,所以你不能只是简单地覆盖函数和变量不理解上下文...

IF功能是全球(看起来像它可能是在这种情况下),你可以inject新的功能定义:

function StartDrawing() { 
    // WHATEVER YOU WANT FOR THE NEW CODE GOES HERE. 
} 

addJS_Node (StartDrawing); 

function addJS_Node (text, s_URL, funcToRun, runOnLoad) { 
    var D         = document; 
    var scriptNode       = D.createElement ('script'); 
    if (runOnLoad) { 
     scriptNode.addEventListener ("load", runOnLoad, false); 
    } 
    scriptNode.type       = "text/javascript"; 
    if (text)  scriptNode.textContent = text; 
    if (s_URL)  scriptNode.src   = s_URL; 
    if (funcToRun) scriptNode.textContent = '(' + funcToRun.toString() + ')()'; 

    var targ = D.getElementsByTagName ('head')[0] || D.body || D.documentElement; 
    targ.appendChild (scriptNode); 
} 


这个工程几乎支持userscripts每一个浏览器。

在某些情况下,您可能需要通过触发窗口load事件和/或检查功能是否已存在来延迟负载。

根据您的浏览器,你可以有更多的选择(见链接的Q & A,上图):

  • 的Firefox + Greasemonkey的,您可以使用@grant none模式或unsafeWindow
  • Chrome + Tampermonkey,通常可以使用unsafeWindow@grant none模式可能起作用,但我自己没有测试过。




如果函数不是全局:

然后在火狐因为它来自于你必须覆盖JS源见"Stop execution of javascript function (client side) or tweak it"

在Chrome中,你大多运气不佳(上次验证六个月前)。

2

如果函数存在,javascript允许重新定义函数。如果重新定义,该函数将被覆盖而没有任何警告。

如果你想让旧功能也可以工作,你可以按照下面的方法。

var _oldStartDrawing =StartDrawing; 
function StartDrawing() { 
    _oldStartDrawing();//if you need previous function 
    //extend code here; 
} 
+0

你有一个错字会导致重大问题。 – Marty

+1

@Marty,你可以编辑它... – epascarello

+0

@epascarello你是对的,我总是忘记那个机制。 – Marty