• 谷歌浏览器插件开发教程7


    从pane发送信息到 inject.js  inject.js发送到pane

    inject.js

    window.addEventListener("message", function(e) {
        var info = e.data;
        var cmd = info.cmd;
        if (cmd == "sendinject") {
            var data = info.data;
            var action = data.action;
            if (action == "begin") {
                window.postMessage({
                    cmd: 'sendcontentscript',
                    data: {
                        action: "begin",
                        list: "开始begin了",
                    }
                }, '*');
            }
            console.log(data);
        }
    }, false);

    contentscript

    function injectCustomJs(jsPath) {
        jsPath = jsPath || 'inject.js';
        var temp = document.createElement('script');
        temp.setAttribute('type', 'text/javascript');
        // 获得的地址类似:chrome-extension://ihcokhadfjfchaeagdoclpnjdiokfakg/js/inject.js
        temp.src = chrome.extension.getURL(jsPath);
        temp.onload = function() {
            // 放在页面不好看,执行完后移除掉
            this.parentNode.removeChild(this);
        };
        document.head.appendChild(temp);
    }
    injectCustomJs();
    // contentscript.js 发送到inject.js
    // 
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        window.postMessage({
            cmd: 'sendinject',
            data: request
        }, '*');
    });
    window.addEventListener("message", function(e) {
        var info = e.data;
        var cmd = info.cmd;
        if (cmd == "sendcontentscript") {
            var data = info.data;
            var action = data.action;
            var list = data.list;
            if (action == "begin") {
                    chrome.runtime.sendMessage({
                        greeting: '你好,我是content-script呀,我主动发消息给后台!'
                    }, function(response) {});
             
            }
            console.log(data);
        }
    }, false);

    mypane.js

    setTimeout(function(){
    
          chrome.tabs.query({active:true, currentWindow:true}, function (tab) {//获取当前tab
                //向tab发送请求
                chrome.tabs.sendMessage(tab[0].id, { 
                    action: "begin",
                    list: "",
                }, function (response) {
                       //test.js的数据
                    console.log(response);
                });
            })
            ;
    
    },200)
    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse)
    {
    
           $('body').html(JSON.stringify(request));
    });

     其实我发现 谷歌浏览器的通信机制并不好用 上面代码是短连接的写法    我打算用websocket代替谷歌浏览器插件通信 

  • 相关阅读:
    Python学习之路【第三篇】--集合
    Python学习之路【第二篇】-pyc简介、Python常用的数据类型及其用法和常用运算符
    Python学习之路【第一篇】-Python简介和基础入门
    NotePad++ 配置Python工作环境
    码农跳槽指南:如何在新公司建立自己的“支配地位”?
    python实现简单的聊天小程序
    真正努力的人,从来不焦虑
    我在公司待了6年,清退我却只花了6分钟
    只有潮水退去后,才知道谁在裸泳
    什么是rpc
  • 原文地址:https://www.cnblogs.com/newmiracle/p/11939866.html
Copyright © 2020-2023  润新知