Ping and Pong Simple Messages

To communicate with the script you must set a localStorage item with some data. The first Item variable name it looks for is 'JR_message_ping_pandacrazy'. The item value isn't important because it only uses the theTarget and url value from the localStorage. I just set the value to an object which must be a string so I use stringify on the object: {"command":"areYouThere","time":datetime})).

  • To send a ping for attention:
    • localStorage.setItem("JR_message_ping_pandacrazy", JSON.stringify({"command":"areYouThere","time":(new Date().getTime())}));

Once the main script gets the message it will send a pong message which uses a unique variable. The variable starts with 'JR_message_pong_' and ends with '_pandacrazy'. So by adding an event for storage you can find any variables that get changed. Watch for the variables that start with ''JR_message_pong' and you will know that the main script is running. That is how I add buttons to mturk pages with the helper script only if the main script is running.

  • For example this is what I used to receive a pong message.
    • window.addEventListener("storage", mainListener, false);
  • In the mainListener function I would look for the key which starts with the pong string. I also make sure there is a newValue and the location is the location for your script.
    • if ( e.key == 'JR_message_pong_' + gScriptName && e.newValue && gLocation == (JSON.parse(e.newValue).url)) {

Now this is a simple ping and pong messaging which is done for simple things like find out if the main script is running. I do recommend to do this so users won't have buttons that do nothing. In fact you don't have to do a ping for some of the external actions for this script but this is a good beginning of how the process of messaging is done.

No questions yet.