Chrome 插件自定义

Chrome 插件自定义
首先介绍一下Chrome插件里面都具体是什么,这里采用了大白话的方式通俗易懂。

插件的核心就是一个json文件:manifest.json 。 具体的结构我就不详细的介绍了,毕竟网络上的相关内容有很多,其次介绍一下background.js 这是一个浏览器内部运行的插件,可以理解是再浏览器中使用,而不是在网页中使用,就像一个作用域一样,它属于外层,而网页属于内层。

其次就是contentScript.js 这个是一个注入到js中的代码,就像我们日常引用的js一样,这个具体的后面细说。最后酒水popup,这是一个在浏览器上的一个窗口,在Chrome中地址栏的右边,点击icon之后会存在一个作用区间,可以在里面执行一些逻辑。

基础的大概的内容就是这些,具体的实现我来记录一下。

先来了解一下我的目录结构
Chrome 插件自定义_第1张图片
首先创建manifest.json

{
 "manifest_version": 2,
 "name": "name",
 "description": "This extension say hello to you.",
   "version": "1.0",
    "permissions": ["tabs", ""],
    "browser_action": {
      "default_icon": "icon.png", //icon图标
     "default_popup": "popup.html" //默认的popup
   },
  "background": {
     "page": "background.html"
   },
  "content_scripts": [{ //引用的js
       "matches": [""],
       "js": ["jquery.js","contentscript.js"]
  }]
}

这里其实没有好介绍的,网上有很多的资料,其次就介绍一下如何进行backgroundjs和popup以及contentScript之间进行发送消息。废话少说,直接上代码:

//background.js
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
    console.log(sender.tab ?
                "from a content script:" + sender.tab.url :
                "from the extension");
    if (request.greeting == "hello")
      sendResponse({farewell: "I'm backgroud,goodbye!"});
  });

//popup.js
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
  chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
  });
});
//contentScript.js
chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});
 
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse) {
			console.log("********************************XPORT****TOOL****************************START******************")
			console.log("open the chrome tool ");
    // if (request.greeting == "hello"){
    //   sendResponse({farewell: "I'm contentscript,goodbye!"});
    // }
  });

以上就是基础的沟通构建 。
剩下的就是可以在contentScript中去创建各种js语言进行操作了,也可以引入jq等框架。
以上就是今天简单研究了一下的理解。
后面附上一个demo源码,使用的方式是点击图中的icon
Chrome 插件自定义_第2张图片

源代码 :https://download.csdn.net/download/xinyuandu/12535748

你可能感兴趣的:(插件,chrome)