0

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 of some sort, but it's not working as I want.

Here's the script:

// ==UserScript==
// @name         My Fancy New Userscript
// @namespace    http://your.homepage/
// @version      0.1
// @description  enter something useful
// @author       You
// @match        *://*/*
// @grant        none
// ==/UserScript==


if (unsafeWindow.resources == undefined) {
   var unsafeWindow.resources = [];
}

var host = window.location;
unsafeWindow.resources.push(host);
console.log(unsafeWindow.resources);

When running it I get the following error:

ERROR: Execution of script 'My Fancy New Userscript' failed! unsafeWindow is not defined

Maybe what I'm trying to do is not even possible?

Update: Trying to be a bit clearer. The end result should result in a dictionary that would have the document.location as key and a dictionary containing the header name and header value of said location as the value.

{document.location = {"Headername" = "Header value", "Headername" = "Header value"}}

The end result will be used to generate a table with the information in the dictionary. Something like this:

enter image description here

/Patrik

PatrikJ
  • 2,327
  • 3
  • 24
  • 35
  • 1
    unsafeWindow.resources will never work as long as it is not defined somewhere (you need to define at least unsafeWindow). Besides, can you please be clearer about what you mean with "Dictionary"? do you need to store these locally or what? – briosheje May 22 '15 at 15:03
  • 1
    I still don't understand what you exactly want to accomplish, to be clearer: the big question is: do you need to KEEP these informations stored or..? In a nutshell, you're trying to fetch every single resource loaded by the DOM and store it in an object to later print a table, is that what you want to do? In any case, keep in mind that using unsafeWindow might open some security holes for your userscript, take a look at this first: https://developer.mozilla.org/en-US/Add-ons/SDK/Guides/Content_Scripts/Interacting_with_page_scripts – briosheje May 22 '15 at 15:38
  • Yes, the information should be stored in Javascript variables for later use. The script generating the information itself will be executed via a bookmarklet (bookmark running a javascript). It won't be public as I plan to run it only on our sites and only manually, so security holes won't be a big problem. Thanks for the link, I will make sure to read it. /Patrik – PatrikJ May 22 '15 at 15:41
  • Oh, and yes. The information will be used to generate a table on demand later on. :) – PatrikJ May 22 '15 at 15:43
  • Okay, now it's a bit clearer. To accomplish such, I highly recommend you to use the **localStorage** instead: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage . Using localStorage, you can store the window.location and **whatever other thing you want to store** and you can access that later by using some comfortable getters (or loop them, like such: http://stackoverflow.com/questions/10083098/loop-search-through-all-items-in-localstorage). In a nutshell, in your usescript, you just push the data you need locally, and access it later when you need to. – briosheje May 22 '15 at 15:44
  • I will try to give you a brief example of what it should look like below, just by saving the urls. – briosheje May 22 '15 at 15:47
  • I have added an example below, take care that it is an example, but it should be close enough to what you want to do. – briosheje May 22 '15 at 16:40

1 Answers1

4

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:

  1. A comfortable DOM object (storage) with three main methods: save (stores key => value, where value must be a string or a json stringified element, because you can't store arrays in local storage), get (get from key) and destroy (from key).
  2. A constructor right at the beginning of domready: if the key holding the elements does NOT exist, it will create it and fill with the current document location, identifying it using the document's href.
  3. A few examples to work with in order to save / retrieve what you need.

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:

enter image description here

http://prntscr.com/784zw7 (picture direct link)

Hope this is helpful for your project ;)

briosheje
  • 7,356
  • 2
  • 32
  • 54
  • Most of the times you get help here on stackoverflow. The majority is great. But then there's people that goes above and beyond. You're awesome dude. It's way past bedtime for me but I'll give it a whirl tomorrow. Thanks a million! – PatrikJ May 22 '15 at 18:56
  • @PatrikJ : you're welcome, I hope it will be helpful to you and whoever will eventually need that in the future ;) – briosheje May 25 '15 at 08:42
  • Does exactly what I wanted it to do. Thanks a million! – PatrikJ May 30 '15 at 15:09