美文网首页让前端飞Web前端之路前端开发
【chrome extensions course】3.调用ap

【chrome extensions course】3.调用ap

作者: bugWriter_y | 来源:发表于2019-06-03 21:11 被阅读2次

除了正常执行js代码以外,extension还可以调用chrome提供的api来实现更多的功能。具体见官网

今天涉及的两个api分别是storage和notifications。

storage用于存储数据,见官网https://developer.chrome.com/apps/storage

notification提供系统级提醒,见官网https://developer.chrome.com/apps/notifications

案例:模拟正常的用户管理,打开页面进入修改页面,默认显示上一次保存的用户名。用户修改数据,点击保存,信息保存完毕,提示用户信息保存完毕。见下图。项目github地址

1.gif
  1. mainfest.json
{
    "manifest_version": 2,
    "name": "storage",
    "version": "1",
    "description": "this is a storage extension",
    "browser_action": {
        "default_popup": "usermanage.html",
        "default_icon": "images/icon16.png"
    },
    "icons": {
        "16": "images/icon16.png",
        "32": "images/icon32.png",
        "48": "images/icon48.png",
        "128": "images/icon128.png"
    },
    "permissions":["storage","notifications"]
}
  1. usermanage.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>storage</title>
    <script src="jquery.min.js"></script>
    <script src="usermanage.js"></script>
</head>

<body>
    <h3>用户名修改</h3>
    <input type="text">
    <button>保存</button>
</body>

</html>
  1. usermanage.js
$(function () {
    //页面打开获取存储的数据,这里使用的是chrome浏览器的storage api
    chrome.storage.local.get("username", function (x) {
        if (x.username) {//如果存在那么给input赋值
            $("input").val(x.username);
        }
    })
    //注册按钮点击事件
    $("button").click(function () {
        //获取用户名
        var username = $("input").val();
        //存储到storage中
        chrome.storage.local.set({ username: username }, function () {
            //创建一个提醒对象
            var notificationItem = {
                type: 'basic',//类型是基本类型(basic,image,list,progress)
                iconUrl: 'images/icon16.png',//图标位置
                title: 'notification',//标题
                message: 'save success',//内容
            }
            chrome.notifications.create("notification", notificationItem)//第一个参数是一个id,尽量系统唯一
        })
    })

})

相关文章

网友评论

    本文标题:【chrome extensions course】3.调用ap

    本文链接:https://www.haomeiwen.com/subject/rygxxctx.html