I\'m trying to write a tampermonkey script which gathers the document.location and headers in a dictionary. Googled a bit and figured I was supposed to use a global variable
Please take this as a brief EXAMPLE of what you should accomplish, and be aware that you may encounter some issues while moving on with your project, because sometimes document.location can be a bit tricky to retrieve.
That apart, the code:
// ==UserScript==
// @name My Fancy New Userscript
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match *://*/*
// @copyright 2015+, You
// ==/UserScript==
var storage = (function(win){
var localDrive = win.localStorage;
return {
save: function (/* <string> */ key, /* <string | JSONstringified object> */ value) {
localDrive.setItem(key, value);
},
destroy: function (/* <string> */ key) {
return localDrive.removeItem(key) ? true : false;
},
get: function (/* <string> */ key) {
return localDrive.getItem(key) == '' || localDrive.getItem(key) == null ? false : localDrive.getItem(key);
}
}
})(window);
window.storage = storage;
document.addEventListener("DOMContentLoaded", function(e) {
// Dom ready, start:
// Check whether the array exists or not :
if (!storage.get("myDataList")) {
storage.save("myDataList", JSON.stringify(
[{
'href' : document.location.href,
'location' : document.location,
'test1' : 'test',
'test2' : 'test2'
}]
)
);
}
else {
// If exists, log every single object:
var currentStorageList = JSON.parse(storage.get("myDataList"));
for (var i = 0; i < currentStorageList.length; ++i) {
console.log(currentStorageList[i]);
}
}
// Check whether this element exists in the current list, else add :
var currentStorageList = JSON.parse(storage.get("myDataList"));
var elementExists = currentStorageList.some(function(el,i,arr) {
return el.href === document.location.href;
});
if (!elementExists) {
console.log("current elements doesn't exist, let's push it!");
storage.save("myDataList", JSON.stringify(JSON.parse(storage.get("myDataList")).push({
'href' : document.location.href,
'location' : document.location,
'test1' : 'test',
'test2' : 'test2'
})));
}
});
This is pure javascript, since I didn't see you using jQuery.
I have provided there:
Please note that this is just an example (it does work, though).
Also, in your tampermonkey script settings, don't forget to set it to run at document-end.
The output on xkcd (for testing) is this:
http://prntscr.com/784zw7 (picture direct link)
Hope this is helpful for your project ;)