在Chrome中的用户脚本之间传输信息 [英] Transferring information between userscripts in Chrome

查看:78
本文介绍了在Chrome中的用户脚本之间传输信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当另一个选项卡中的某些条件满足时,我需要在一个选项卡的页面上执行一个函数.我需要做的就是向其他选项卡发送某种轻推.我已经尝试过与计时器配合使用以保持轮询的很多事情:

I need to have a function execute on a page in one tab when certain conditions are met in another tab. All I need to do is send some kind of nudge to the other tab. I've tried many things already in conjunction with a timer to keep polling:

  • GM_setValue(Chrome显然不支持)
  • 设置top.item(在选项卡之间显然不起作用)
  • Cookie(即使我的用户脚本在同一个域中的两个选项卡中运行,这似乎也不起作用)

还有其他想法吗?是的,我确实需要使用Chrome,即使它似乎有意在此>.>

Any other ideas? And yes, I do need to use Chrome, even though it seems intent on thwarting me in this >.>

推荐答案

由于选项卡位于同一域中,因此可以使用localStorage.

Since the tabs are on the same domain, you can use localStorage.

  1. 将脚本设置为在两个页面(例如EG)上运行:

  1. Set the script to run on both pages, EG:

// @include  http://YOUR_SERVER.COM/YOUR_PATH/pitcher/*
// @include  http://YOUR_SERVER.COM/YOUR_PATH/batter/*

  • 请确保您可以分辨出哪个页面.例如,通过URL或其他一些内容.

  • Be sure you can tell which page is which. By the URL, for example, or some different content.

    发送页面仅根据需要设置值,例如:

    The sending page merely sets values as desired, EG:

    localStorage.setItem ('targetAddress', 'http://puppies.com/');
    

  • 接收页面侦听storage事件,例如:

  • The receiving page listens for storage events like:

    $(window).bind ("storage", function (zEvent) {
        ...
    } );
    

    window.addEventListener ("storage", function (zEvent) {
        ...
    }, false);
    


  • 综上所述,这是一个完整的脚本,该脚本可在Firefox和Chrome(以及可能的Opera和其他浏览器)中使用.


    Putting it all together, here is a complete script, that works in both Firefox and Chrome (and probably Opera and others).

    您可以针对 此发件人"页面 进行测试,和 此接收者"页面 .

    You can test it against this "sender" page, and this "receiver" page.

    // ==UserScript==
    // @name     _Cross tab, same domain communication
    // @include  http://jsbin.com/ihoboz/*pitcher*
    // @include  http://jsbin.com/ihoboz/*batter*
    // @include  http://YOUR_SERVER.COM/YOUR_PATH/pitcher/*
    // @include  http://YOUR_SERVER.COM/YOUR_PATH/batter/*
    // @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
    // @grant    GM_addStyle
    // ==/UserScript==
    /*- The @grant directive is needed to work around a design change
        introduced in Greasemonkey 1.0.   It restores the sandbox.
    */
    
    function GM_main ($) {
        /*-- Is this the sending or receiving page?
            In our example, the sender has "pitcher" in the URL,
            while the receiver has "batter" in the URL
        */
        var isSender = false, isReceiver = false;
    
        if (/pitcher/i.test (location.href) ) {
            isSender    = true;
        }
        else if (/batter/i.test (location.href) ) {
            isReceiver  = true;
        }
    
        if (isSender) {
            //-- Add 2 buttons to change the data we send to the other tab.
            $("body").prepend (
                '<button class="gmTestButtons">Set the transmitted value.</button>' +
                '<button class="gmTestButtons">Reset the transmitted value.</button>'
            );
    
            $("button.gmTestButtons").click ( function () {
    
                if (/^Set the transmitted/.test (this.textContent) ) {
                    localStorage.setItem ('targetAddress', 'http://puppies.com/');
                }
                else {
                    localStorage.setItem ('targetAddress', 'http://unicorns.com/');
                }
            } );
        }
        else if (isReceiver) {
            //-- Listen for changes in local storage
            $(window).bind ("storage", function (zEvent) {
                var varName     = zEvent.originalEvent.key;
                var newValue    = zEvent.originalEvent.newValue;
    
                alert (
                    'Received new variable, "'   + varName
                    + '", with a new value of: ' + newValue
                );
            } );
        }
    }
    
    //-- Style and/or postion our buttons
    GM_addStyle ( "                                 \
        button.gmTestButtons {                      \
            margin:                 1em;            \
            padding:                1ex 1em;        \
            font-size:              20px;           \
            background:             pink;           \
        }                                           \
    " );
    
    
    //--- The rest of this just loads jQuery in a cross-browser way.
    //
    if (typeof jQuery === "function") {
        console.log ("Running with local copy of jQuery!");
        GM_main (jQuery);
    }
    else {
        console.log ("fetching jQuery from some 3rd-party server.");
        add_jQuery (GM_main, "1.7.2");
    }
    
    function add_jQuery (callbackFn, jqVersion) {
        var jqVersion   = jqVersion || "1.7.2";
        var D           = document;
        var targ        = D.getElementsByTagName ('head')[0] || D.body || D.documentElement;
        var scriptNode  = D.createElement ('script');
        scriptNode.src  = 'http://ajax.googleapis.com/ajax/libs/jquery/'
                        + jqVersion
                        + '/jquery.min.js'
                        ;
        scriptNode.addEventListener ("load", function () {
            var scriptNode          = D.createElement ("script");
            scriptNode.textContent  =
                'var gm_jQuery  = jQuery.noConflict (true);\n'
                + '(' + callbackFn.toString () + ')(gm_jQuery);'
            ;
            targ.appendChild (scriptNode);
        }, false);
        targ.appendChild (scriptNode);
    }
    

    这篇关于在Chrome中的用户脚本之间传输信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆