首先,让我们创建一个空文件夹来存放扩展程序的内容。定义扩展程序所需的最少文件是清单,它告诉 Chrome 扩展程序的定义特征

文件夹中创建一个名为的文件: manifest.json

{
    "manifest_version":3,
    "version":"1.0",
    "name":"Simple Bookmarker",
    "action":{
      "default_popup":"index.html"
  },
    "icons":{
        "16":"images/logo16.png",
        "48":"images/logo48.png",
        "64":"images/logo64.png",
        "128":"images/logo128.png"
    },
    "description":"A Simple bookmarker.Features include :  Saving custom input, Saving current tab, etc",
    "permissions":[
        "tabs"
    ],
    "author":"Omkar Bhoir"
}
  • Manifest_version: 如果您可能需要使用不同格式的manifest,您可以查看 Chrome 接受的其他manifest_version
  • Background: 可以在此处放置在扩展程序后台运行的脚本
  • Permissions: 这些是您使用扩展程序访问的 API。 在这里,我们将使用 storage 来存储持久性数据,activeTab,检查活动选项卡,以及脚本,在活动选项卡上运行操作
  • Action: 可以在此处放置扩展程序的不同类型的组件。 对于这个例子,我们只是要创建一个弹出菜单,并告诉 Chrome 从 popup.html 中获取弹出菜单

代码

第一部分绝不是必需的,但我认为向您展示持久性数据存储和后台脚本的工作方式很有帮助。让我们创建一个名为background.js

let color = "#fa9639"


// 在用户第一次安装扩展时运行chrome.runtime.onInstalled.addListener(() => {
    chrome.storage.sync.set({color}) // Use sync to store persistent data
    console.log("Button Color Set")
})

创建popup.html文件,当然您可以创建一个单独的 CSS 文件,但为了简单起见,我们将只使用样式标签

<html>
  <head>
    <style>
      button {
        margin: 10px;
        border-radius: 2px;
        border: 1px solid black;
        font-family: "Comic Sans MS";
      }

    </style>
  </head>
  <body>
    <h1>Comic Sans Is King</h1>
    <button id="changeFont">Swap Font</button>
    <script src="popup.js"></script>
  </body>
</html>

最后,让我们在按下按钮时实际转换为 Comic Sans。popup.js使用以下代码创建一个文件

// Snag our button
let btn = document.getElementById("changeFont")

// Set our button's color to the color that we stored
chrome.storage.sync.get("color", ({color}) => {
    btn.style.backgroundColor = color
})

// Run on click
btn.addEventListener("click", async () => {
    let [tab] = await chrome.tabs.query({active: true, currentWindow:true}) // Find current tab

    chrome.scripting.executeScript({ // Run the following script on our tab
        target: {tabId: tab.id},
        function: () => {
            let elems = document.querySelectorAll("*"); // Grab every element in the dom
            for (var i = 0;i < elems.length; i++){ 
                elems[i].style.fontFamily = "Comic Sans MS";
            }
        }
    })
})

下一步是将其加载到 Chrome 中

将我们的扩展加载到 chrome 中再简单不过了。使用 url 转到扩展菜单

chrome://extensions/

确保已启用开发人员模式(可以在右上角完成), 点击加载已解压的扩展程序,选择我们所有扩展文件所在的文件夹,然后将加载扩展

现在可以像这样使用它

image.png

上传到 Chrome 商店

在公共 Chrome 商店中获取您的应用程序是一种完全不同的考验,Chrome 记录得非常好

https://developer.chrome.com/docs/webstore/publish/

点赞(0)

评论列表 共有 0 评论

暂无评论

微信服务号

微信客服

淘宝店铺

support@elephdev.com

发表
评论
Go
顶部