Greasemonkey: Passing unique string data to opened tabs?

Created on 7 Nov 2015  ·  10Comments  ·  Source: greasemonkey/greasemonkey

Now that GM_openInTab no longer returns the window object, and thus we can't set window variables from the script that opens the window, how can one pass unique string data to a tab, designated for just that tab?

All 10 comments

That simply confirms that GM_openInTab returns null, but doesn't make reference to my use case.

one workaround would be to add an anchor to the URL and have a script process that anchor. For larger payloads you could use that anchor as ID and then use broadcast channels to have the tabs talk to each other.

Note that web content can listen/manipulate these kinds of communication channels.

I would avoid anchors for that very reason.

You can use GM_info.uuid label communication channel with it.
As script UUID unique for script+computer+profile it's safe enough.
PS: Don't forget to // @grant GM_info in metadata block.

That sounds like it's for communicating between different scripts, not the same script running on a new page.

@Sasstraliss Why do you think "it's for communicating between different scripts"? Script can't get UUID of different script - only UUID of the same.

Here's a trick I learned from reddit. A fair amount of pseudocode as far as variables are concerned, but it might help. Assuming the target window and parent window are on sites the script is for...

var stringData;

var awakener = window.opener || window.parent;
if(awakener && awakener != window)
{
    //Used when a page is launched from a link so that passData can...well...pass data. But we can't use onload from there so instead we're using postMessage here to convey to the "parent" window that this window is ready to recieve data
    awakener.postMessage("Loaded","*");
}

window.addEventListener("message", messageDetected, false);

clickableThing.onclick = function() {
    var newWindow = window.open(this.href,this.target);
    passData(window,newWindow,dataToPass);
    return false;
};

function messageDetected(event)
{
    if(typeof(event.data) == "string" && event.data != "Loaded")
    {
        stringData = event.data;
    }
}

function passData(mainWindow,target,data)
{
    mainWindow.addEventListener("message", passItOn, false);
    function passItOn(event)
    {
        if(event.source == target) target.postMessage(data,"*");
    }
}

@DoomTay, please use triple backquotes to keep source formatting.

@the8472 said:

use broadcast channels

Alas, this is experimental technology only available in Fx38+. A more appropriate solution would be using localStorage API and storage events. see http://stackoverflow.com/questions/2236828/javascript-communication-between-tabs-windows-with-same-origin/12514384#12514384

Was this page helpful?
0 / 5 - 0 ratings