zoukankan      html  css  js  c++  java
  • 谷歌插件消息传递

    谷歌插件消息传递
    1.简单消息传递
    a.应用->脚本
    chrome.runtime.sendMessage({greeting: "您好"}, function(response) {
     console.log(response.farewell);
    });
    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "来自内容脚本:" + sender.tab.url :
                    "来自应用");
       if (request.greeting == "您好")
         sendResponse({farewell: "再见"});
    }
    );

    b.脚本->应用

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
     chrome.tabs.sendMessage(tabs[0].id, {greeting: "您好"}, function(response) {
       console.log(response.farewell);
     });
    });
    chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        console.log(sender.tab ?
                    "来自内容脚本:" + sender.tab.url :
                    "来自应用");
       if (request.greeting == "您好")
         sendResponse({farewell: "再见"});
    }
    );
    //tabs[0].id为tab的id值
    2.持久链接
    a.应用->脚本
    var port = chrome.runtime.connect({name: "敲门"});
    port.postMessage({joke: "敲门"});
    port.onMessage.addListener(function(msg) {
     if (msg.question == "是谁?")
        port.postMessage({answer: "女士"});
     else if (msg.question == "哪位女士?")
        port.postMessage({answer: "Bovary 女士"});
    }
    );
    b.脚本->应用
    runtime.connect替换为 tabs.connect
     
     
  • 相关阅读:
    第一章 第二节逻辑代数基础
    第一章 第一节数制与编码
    Altium Designer多原理图、PCB更新处理
    AD添加LOGO的方法
    XML中<beans>属性
    程序员值得学习的技术博客
    设计模式
    js分页实例
    Java构造和解析Json数据的方法
    H5+ 移动app学习之三 App离线存储
  • 原文地址:https://www.cnblogs.com/luotingliang/p/7251434.html
Copyright © 2011-2022 走看看