Chrome扩展中的界面

图标弹窗(popup)

图标弹窗

注册:

在清单文件的浏览器行为(browser_action),添加默认弹窗(default_popup)

 {
    
    
    "name": "My Extension",
    "version": "2.1",
    "description": "Gets information from Google.",
    "icons": {
    
    
      "128": "icon_16.png",
      "128": "icon_32.png",
      "128": "icon_48.png",
      "128": "icon_128.png"
    },
    "background": {
    
    
      "persistent": false,
      "scripts": ["background_script.js"]
    },
    "permissions": ["https://*.google.com/", "activeTab"],
    "browser_action": {
    
    
      "default_icon": "icon_16.png",
      "default_popup": "popup.html"
    }
  }

编写

编写popup.html,就可以在弹窗的展示出来。
比如下面的HelloWorld入门程序

  • 清单
{
    
    
  "name": "HelloWorld",
  "version": "1.0.0",
  "manifest_version": 2,
  "description": "This a extension with a UI of HelloWorld",
  "icons":
  {
    
    
    "128": "image/image128.png",
    "48": "image/image48.png",
    "16": "image/image16.png"
  },
  "browser_action":
  {
    
    
    "default_icon": "image/image16.png",
    "default_popup": "popup.html"
  }
}

  • popup.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HelloWorld</title>
    <script src="jquery-3.5.1.min.js">
    </script>
    <script src="popup.js"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1 id="greet">Hello World!</h1>
<input type="text" id="name">
</body>
</html>
  • popup.js
$(function (){
    
    
    $('#name').keyup(function () {
    
    
        $('#greet').text('Hello '+$('#name').val())
    })
})

注意文件存放的位置,不然可能识别不到。

选项页

选项

注册

{
    
    
  "name": "My extension",
  ...
  "options_page": "options.html",
  ...
}

编写

编写好选项页,会在标签页中展示。
沙拉查词的选项页

用法

选项页与其他脚本的通信是通过,Chrome的API,比如storage,runtime等,下面有一个预算计算器,展示了弹窗,选项页,以及后台脚本之间如何通过ChromeAPI进行交流。chromeAPI如何使用参考官方文档,一般来说存贮数据storage使用set,get方法,set,一个参数接受一个键值对,第二个参数是回调函数,get方第一个参数接受键,并传入一个回调函数。

        chrome.storage.sync.set({
    
    key: value}, function() {
    
    
          console.log('Value is set to ' + value);
        });
        chrome.storage.sync.get(['key'], function(result) {
    
    
          console.log('Value currently is ' + result.key);
        });

示例

  • 清单
{
    
    
  "manifest_version": 2,
  "version": "1.0",
  "name":"Budget Manager",
  "description": "This is a extension that helps you manager bill",
  "icons": {
    
    
    "128": "image/image128.png",
    "48": "image/image48.png",
    "16": "image/image16.png"
  },
  "browser_action": {
    
    
    "default_icons": "image/image/16",
    "default_popup": "popup.html"
  },
  "background": {
    
    
    "scripts": ["eventPage.js"],
    "persistent": false
  },
  "options_page": "option.html",
  "permissions": [
    "storage",
    "notifications",
    "contextMenus"
    ]

}
  • popup.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Budget Manager</title>
    <script src="jquery-3.5.1.min.js"></script>
    <script src="popup.js"></script>
</head>
<body>
<h1>Budget Manager</h1>
<h2>Total Spend:<span id="total">0</span></h2>
<h2>limit:<span id="limit"></span></h2>
<h3>Enter Amount:</h3>
<input type="text" id="amount"/>
<input type="submit"id="spendAmount" value="Spend">
</body>
</html>
  • popup.js
$(function (){
    
    
    chrome.storage.sync.get(['total','limit'],function (budget){
    
    
        $('#total').text(budget.total)
        $('#limit').text(budget.limit)
    })
    $('#spendAmount').click(function () {
    
    
        chrome.storage.sync.get(['total','limit'],function (budget){
    
    
            let newTotal=0;
            if(budget.total){
    
    
                newTotal+=parseInt(budget.total)
            }

            let amount = $('#amount').val();
            if(amount){
    
    
                newTotal+=parseInt(amount)
            }
            chrome.storage.sync.set({
    
    'total':newTotal},function () {
    
    
                if(amount>=budget.limit && newTotal >=budget.limit){
    
    
                  let  notifOptions={
    
    
                      type:'basic',
                      iconUrl:'image/image48.png',
                      title:'Out of limit',
                      message:"Please Reset the total or limit"
                    };
                    chrome.notifications.create('LimitNotification',notifOptions)
                }

            });
            $('#total').text(newTotal)
            $('#amount').val('')
        })
    })
})
  • option.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Budget Manager Options</title>
    <script src="jquery-3.5.1.min.js"></script>
    <script src="option.js"></script>
</head>
<body>
<h1>Budget Manager Options</h1>
<h2>Limit:<input type="text" id="limit"></h2>
<input type="submit" id="saveLimit" value="Save Limit">
<input type="submit" id="resetTotal" value="Reset Total">
</body>
</html>
  • option.js
$(function () {
    
    
    chrome.storage.sync.get('limit',function (budget) {
    
    
        $('#limit').val(budget.limit)
    })
    $('#saveLimit').click(function () {
    
    
        let limit=$('#limit').val()
        chrome.storage.sync.set({
    
    'limit':limit},function () {
    
    
            close()
        })
    })
    $('#resetTotal').click(function () {
    
    
        chrome.storage.sync.set({
    
    'total':0})
    })
})

上下文菜单

沙拉查词
沙拉查词中有很多菜单,内容十分丰富。我们通过chromeAPI的contextMenus实现这种效果

注册:

   {
    
    
        "name": "My extension",
        ...
        "permissions": [
          "contextMenus"
        ],
        "icons": {
    
    
          "16": "icon-bitty.png",
          "48": "icon-small.png",
          "128": "icon-large.png"
        },
        ...
      }

请求权限后便可以使用这一API

用法

creat,update,remove,removeAll,他们接受的参数大体相同
API

上下文菜单显示有两个位置,页面和图标,下图是页面右击的菜单

上下文菜单要想在图标出显示,须在contexts属性设为broswe_action

实例:

chrome.contextMenus.create({
    
    
    id:"wordbook",
    contexts:["browser_action"],
    title:"生词本"
    
})
chrome.contextMenus.onClicked.addListener(function (clickData) {
    
     if(clickData.menuItemId=="wordbook"){
    
    
        chrome.tabs.create({
    
    url:"wordbook.html"})
    })

页面弹窗

页面弹窗采用Js注入的方式,在chrome能访问网页dom的脚本只有content_script,以来这一特性,可以利用内容脚本向网页注入js

注册:

{
    
    
  "manifest_version": 2,
  "name": "Killer",
  "version": "1.0",
  "description": "This a extension that handles SB_ZHI_HU",
  "icons": {
    
    
    "128": "image/image128.png",
    "48": "image/image48.png",
    "16": "image/image16.png"
  },
  "content_scripts":[
    {
    
    
      "matches": ["https://www.zhihu.com/*","http://223.2.10.172/*"],
      "js": ["jquery-3.5.1.min.js","content.js"]
    }
  ],
  "permissions": [
    "https://www.zhihu.com/*",
    "http://223.2.10.172/*"
  ]

}

用法:


let popContent=" <div class=\"pop\" style=\"width: 100px;height: 100px\">\n" +
    "    <style type=\"text/css\">\n" +
    "        .pop{\n" +
    "            position: absolute;\n" +
    "            left: 20px;\n" +
    "            top:60px;\n" +
    "            background-color:rgba(0,0,0,0);\n" +
    "            border: solid 2px;\n" +
    "        }\n" +
    "    </style>\n" +
    "    <button id=\"close\">关闭</button>\n" +
    "</div>"
$("body").append(popContent)
$("#close").on("click",function () {
    
    
    $("div.pop").remove()
})


效果:
在这里插入图片描述
点击关闭:在这里插入图片描述

其他方式——后台注入:

利用后台脚本在标签页打开时也可以注入js脚本

 chrome.runtime.onMessage.addListener(
    function(message, callback) {
    
    
      if (message == “changeColor”){
    
    
        chrome.tabs.executeScript({
    
    
          code: 'document.body.style.backgroundColor="orange"'
        });
      }
   });

或者

 chrome.runtime.onMessage.addListener(
    function(message, callback) {
    
    
      if (message == “runContentScript”){
    
    
        chrome.tabs.executeScript({
    
    
          file: 'contentScript.js'
        });
      }
   });

下面这个沙拉查词的弹窗就做得很好看
在这里插入图片描述

弹窗

其他:

  • WebStorm可以导入JS的chrome库,编写效率会大大提高:
  • 沙拉查词开源而且界面好看,基本涉及到了所有知识,值得我们去学习。
    Github:https://github.com/crimx/ext-saladict

猜你喜欢

转载自blog.csdn.net/m0_47202518/article/details/108924006