7

我已经开始编写一个greasemonkey脚本,并且正面临在Greasemonkey脚本中执行localstorage的问题。我可以在GM中找到本地存储的唯一方法是在newElement.innerHTMLDOM属性中创建另一个Javascript实例,但其余变量无法访问。Greasemonkey中的LocalStorage

任何想法?这是我正在研究的Greasemonkey代码片段。

 var testHref = anchorTag[i].href; 
    var testHTML = anchorTag[i].innerHTML; 
    var patHref = /item\?id=[0-9]*/g; 
    var patCaptureId = /item\?id=([0-9]*)/g; 
    var testId = patCaptureId.exec(testHref); 
    var patHTML = /[0-9]* comment(|s)/g; 
    var patHTML2 = /discuss/g; 
    if(patHref.test(testHref) && !patHTML.test(testHTML) && !patHTML2.test(testHTML)) 
    { 
     newElement = document.createElement('span'); 
     newElement.style.color = "#FF0000"; 
     newElement.innerHTML = "<a href=\"javascript:localStorage.setItem('one', 'rishabhVerma'); var test = localStorage.getItem('one'); console.log(test);\"> B</a>"; 
     anchorTag[i].parentNode.insertBefore(newElement, anchorTag[i].nextSibling); 
    } 
    i++; 

回答

7

嗯,unsafeWindow.localStorage不工作,我猜?我知道这对获得localStorage的Chrome来说并不是问题,但从来没有在firefox上尝试过,说实话。

+4

这似乎很好地工作。 – 2011-03-28 19:16:01

+1

请注意,使用unsafeWindow将允许网页检测并潜在地缩小greasemonkey,如果它能够捕获调用unsafeWindow对象时发生的事件。 该信息可以被验证[这里](https://www.safaribooksonline.com/library/view/greasemonkey-hacks/0596101651/ch01s13.html) – CoasterChris 2015-04-04 18:42:19

9

如果你只需要存储值,你可以使用经典的Greasemonkey方式,使用GM_getValue()GM_setValue()函数,这些函数工作得很好。

+0

@Basilevs在另一方面,非常大量的数据_will_原因localStorage吐出你的例外;-) – 2014-05-29 09:21:14

+0

@JanDvorak我对数据量的评论已不再相关 - Greasemonkey [使用SQLite存储值](http://stackoverflow.com/a/20976405/125562)。 – Basilevs 2014-05-29 15:00:06