Greasemonkey: 将唯一的字符串数据传递给打开的选项卡?

创建于 2015-11-07  ·  10评论  ·  资料来源: greasemonkey/greasemonkey

现在 GM_openInTab 不再返回窗口对象,因此我们无法从打开窗口的脚本中设置窗口变量,如何将唯一的字符串数据传递给仅指定给该选项卡的选项卡?

所有10条评论

另请参阅https://github.com/greasemonkey/greasemonkey/issues/2134
(仅用于上下文)

这只是确认 GM_openInTab 返回 null,但没有参考我的用例。

一种解决方法是在 URL 中添加一个锚点,并有一个锚点的脚本进程。 对于较大的有效负载,您可以使用该锚点作为 ID,然后使用广播频道让选项卡相互交谈。

请注意,Web 内容可以侦听/操纵这些类型的通信渠道。

出于这个原因,我会避免使用锚。

您可以使用GM_info.uuid标签与它通信。
作为脚本+计算机+配置文件独有的脚本UUID,它足够安全。
PS:不要忘记在元数据块中添加// <strong i="8">@grant</strong> GM_info

这听起来像是用于不同脚本之间的通信,而不是在新页面上运行的相同脚本。

@Sasstraliss为什么您认为“这是为了在不同脚本之间进行通信”? 脚本无法获取不同脚本的 UUID - 只有相同的 UUID。

这是我从 reddit 学到的一个技巧。 就变量而言,有相当多的伪代码,但它可能会有所帮助。 假设目标窗口和父窗口位于脚本所针对的站点上...

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 ,请使用三重反引号来保持源格式。

@the8472说:

使用广播频道

唉,这是仅在 Fx38+ 中可用的实验性技术。 更合适的解决方案是使用localStorage API 和存储事件。 http://stackoverflow.com/questions/2236828/javascript-communication-between-tabs-windows-with-same-origin/12514384#12514384

此页面是否有帮助?
0 / 5 - 0 等级