Blog

Blog

PHODAL

Chrome 插件开发 Content Scripts与后台通讯

记录一下Chrome 插件开发的一些小Tips。

Chrome Bagde设置

代码如下:

chrome.browserAction.setBadgeBackgroundColor({color: '#c8112f'});
chrome.browserAction.setBadgeText({text: number, tabId: tabID });

Chrome 前后台通讯

Chrome 通讯 Background

后台代码

            chrome.runtime.onConnect.addListener(function (port) {
                port.postMessage({
                    type:"info",
                    totalResultsCount: count,
                    where: where
                });
            });

消息的内容是

{type:"info", totalResultsCount: count, where: where }

于是在前台我们可以这么写。

Chrome 通讯 Content Scripts

当消息的类型是info时,我们就从消息中读取相应的内容。

port.onMessage.addListener(function(message, sender){
    if(message.type === "info"){
        if($('#header').length === 0){
            $("html").append("<div id='header'>" +
            " <div class='header'>We found " + message.totalResultsCount  + " results in " + message.where + "</div></div>");
        }
    }
});

或许您还需要下面的文章:

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签