chrome插件的开发案例分析

chrome插件的开发案例分析

chrome插件开发案例分享,通过chrome插件来给我们系统页面添加辅助功能,即发送一些需要的数据和进行一些浏览器本地的存储功能。

仓库地址

  • chrome-plugin-example@github

Chrome 插件中manifest.json的主要设置

{
    "permissions": [
        "http://localhost:3000/*",
        "tabs",
        "storage"
    ],
    "content_scripts": [{
        "matches": ["http://localhost:3000/*"],
        "js": ["js/hacker.js"]
    }]
}

Chrome 插件界面的布局

<body>
<form id="form">
    <input id="db" type="text" placeholder="please input your db name"><br>
    <input id="category" type="text" placeholder="please input your category name"><br>
    <input id="user" type="text" placeholder="please input your user name"><br>
    <button type="submit" id="btn">Sendbutton>
form>
body>
<script src="js/index.js">script>

Chrome插件的主要逻辑

index.js code:

chrome.tabs.query({active: true, lastFocusedWindow: true}, function (tabs) {
    var btn = document.querySelector('#btn');
    var db = document.querySelector('#db');
    var category = document.querySelector('#category');
    var user = document.querySelector('#user');

    // get browser local storage
    chrome.tabs.sendMessage(tabs[0].id, {action:'getStorage'}, function(resp){
        if(!resp) {
            return;
        }
        db.value = resp.db;
        category.value = resp.category;
        user.value = resp.user;
    }); 

    // send button click event handler
    btn.onclick = function () {
        var messageData = {
            action: 'clickSend',
            list: {
                db: db.value,
                category: category.value,
                user: user.value
            }
        };

        chrome.tabs.sendMessage(tabs[0].id, messageData); // chrome send message here
    }
});

Chrome 插件中插入当前允许域名下的脚本

hacker.js code

chrome.extension.onMessage.addListener(
    function(request, sender, sendResponse) {
        if (request.action === "clickSend") {
            var postData = getInputsGui(document, request.list); // get data
            handlePostAjax(postData, request.list, 'http://127.0.0.1:3000/');
        }

        if (request.action === "getStorage") {
            var chromePluginStore = localStorage.chromePlugin;
            sendResponse(chromePluginStore ? JSON.parse(chromePluginStore) : null);
        }
    });

// get guis from chosen inputs
function getInputsGui(d, messageData) {
    var inputs = d.querySelectorAll('input[type="checkbox"]');
    var inputsArray = []; // input array list
    for (var i = 0; i < inputs.length; i++) {
        if (inputs[i].checked) {
            inputsArray.push(inputs[i].getAttribute('gui'));
        }
    }
    var postData = [];
    for (var i = 0; i < inputsArray.length; i++) {
        var item = {};
        item.Gui = inputsArray[i] || 'test';
        item.Db = messageData.db || 'test';
        item.Category = messageData.category || 'test';
        item.User = messageData.user || 'test';
        postData.push(item);
    }
    return postData;
}

// handle post method
function handlePostAjax(postData, list, url) {
    var xhr = new XMLHttpRequest();
    xhr.open('post', url); // send an request
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // set request header
    xhr.send(JSON.stringify(postData)); // send to server

    xhr.onreadystatechange = function() {
        if ((xhr.readyState === 4) && (xhr.status === 200)) {
            localStorage.chromePlugin = JSON.stringify(list); // for local storage
            alert('send success!');
        } else if ((xhr.readyState === 4) && (xhr.status !== 200)) {
            alert('fail');
        }
    }
}

上面这段脚本将会插入在测试域名的页面下,来响应chrome插件中的点击事件

服务端响应chrome发送数据的处理

主要程序:

'use strict';

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

    let url = req.url;
    let method = req.method;

    if(url === '/' && method === 'GET') {
        fs.createReadStream(__dirname + '/index.html', 'utf8').pipe(res);
    }else if (url === '/' && method === 'POST') {
        parsePostData(req, (data) => {
            console.log(data); // log request data
            res.end('post received');
        });
    };
});

server.listen(3000, '127.0.0.1', function() {
    console.log('server is listening @ port 3000');
});

function parsePostData(req, callback) {
    let data = '';
    req.on('data', (chunk) => {
        data += chunk;
    });
    req.on('end', () => {
        callback(data);
    })
}

服务端需要渲染的页面 index.html 主要代码:

<ul>
  <li><input type="checkbox" gui="gui1">gui1li>
  <li><input type="checkbox" gui="gui2">gui2li>
  <li><input type="checkbox" gui="gui3">gui3li>
  <li><input type="checkbox" gui="gui4">gui4li>
  <li><input type="checkbox" gui="gui5">gui5li>
ul>

测试

在测试域名下:http://127.0.0.1:3000/ 下,通过chrome插件,你就可以发送想要获取的页面数据了。

你可能感兴趣的:(Javascript,Web,Chrome,Chrome,plugin,谷歌插件开发)