![](/img/trans.png)
[英]Replaceing/swapping JavaScript file in html using Greasemonkey
[英]Storing into file using JavaScript/GreaseMonkey
我使用 Greasemonkey 从页面中捕获了数据列表。
通用脚本
var hit = GM_getValue("hit") || 0;
var _url = "http://localhost:8080/test?p=$$pageNo$$";
_url = _url.replace("$$pageNo$$", hit);
GM_setValue("hit", ++hit);
if(hit <= 100) {
window.location.href = _url;
}
该脚本将运行第 n 次并捕获 <10K 数据,现在我面临将捕获的数据存储在某个文件中的问题。 任何人都知道我们如何将捕获的数据存储到文件/存储库中?
谢谢 - 维斯瓦纳坦 G
一个非常快速和简单的解决方案是使用FileSaver.js :
1) 将以下行添加到 Greasemonkey 脚本的 ==UserScript== 部分
// @require https://raw.githubusercontent.com/eligrey/FileSaver.js/master/FileSaver.js
2)在GM脚本中添加以下2行代码
var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");
此代码示例将显示一个对话框,用于下载名为“hello world.txt”的文件,其中包含文本“Hello, world!”。 只需将其替换为您选择的文件名和文本内容即可!
不,不能将它写入文件,但是如果您真的很无聊,可以将它发布到http://pastebin.com (或任何其他接受带有一堆数据的 POST 请求的 URL)。
GM_xmlhttpRequest({
method: "POST",
url: "http://pastebin.com/post.php",
data: <your data here>,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
alert("posted");
}
});
请注意,您需要有一个 pastebin 帐户才能使用该 API。
如果您确实需要将文件写入本地文件系统,请在桌面上运行 Web 服务器,然后将 http PUT 请求的结果保存到磁盘。
我使用这个技巧从 Tampermonkey 脚本下载文件:
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "octet/stream"});
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
然后调用它:
saveData("this data will be written in the file", "file.txt");
它的工作原理是创建一个隐藏元素并模拟该元素被点击。 它的行为就像用户单击了下载链接一样,因此该文件将由浏览器下载,并保存在浏览器放置下载文件的任何位置。
是的,您可以写入文件。 但不是系统中的任何地方,出于明显的安全原因,您可以只写在cookies目录中
var cookie_name="YourCookie";
var cookie_value="What you want to save inside your cookie";
var d = new Date();
d.setTime(d.getTime() + (28*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cookie_name +"=" + cookie_value + ";" + expires + ";path=/";
然后你可以
根据您的操作系统,将 cookie 目录中的文件复制脚本到您的桌面
或从 Chrome Inspect -> Application -> Cookies 读取值
或检索 Cookie 并将其打印在控制台中
decodeURIComponent(document.cookie);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.