javascript浏览器_如何使用JavaScript和浏览器API进行跨浏览器扩展

javascript浏览器

by ryanwhocodes

通过ryanwhocodes

如何使用JavaScript和浏览器API进行跨浏览器扩展 (How to make a cross-browser extension using JavaScript and browser APIs)

This tutorial will cover how to create a web extension that works across multiple browsers. It will show you how to structure a project and write JavaScript code to interact with the browser’s tabs, depending on which browser is being used. This means you can code and then distribute one extension package to multiple browsers’ web stores.

本教程将介绍如何创建可在多个浏览器上使用的Web扩展。 它将向您展示如何构造项目以及编写JavaScript代码以与浏览器的选项卡进行交互,具体取决于所使用的浏览器。 这意味着您可以编写代码,然后将一个扩展程序包分发到多个浏览器的网络商店。

This post will focus on the Chrome and Firefox browsers, along with distributing extensions via the Chrome Web Store and Firefox Add-ons websites. Other browsers and distribution options are also available for web extensions.

这篇文章将重点介绍Chrome和Firefox浏览器,以及通过Chrome网上应用店Firefox附加组件网站分发扩展程序 。 其他浏览器和分发选项也可用于Web扩展。

Get started with a template — copy, edit and publish!

开始使用模板 -复制,编辑和发布!

To see a completed example, here’s a link to an extension I made called Link Formatter, with the cross-browser JavaScript within popup.js. The same package is listed in both the Chrome and Firefox web stores.

要查看完整的示例,下面是指向我做的名为Link Formatter的扩展的链接,该扩展带有popup.js中的跨浏览器JavaScript。 Chrome和Firefox网络商店中都列出了相同的软件包。

浏览器扩展 (Browser extensions)

Extensions are a fantastic way to extend the functionality of your browser, and they allow you to improve your experience online. If you are building your first one or want to learn more about them, I recommend the following tutorials:

扩展程序是一种扩展浏览器功能的绝妙方法,它使您可以改善在线体验。 如果您要构建第一个或想要了解它们的更多信息,我建议您使用以下教程:

将扩展程序本地加载到计算机上 (Load your extension locally on your computer)

When developing your extension, you can load it locally without having to publish and download it from an external website. The way you do this depends on which browser you are using.

开发扩展程序时,您可以在本地加载它,而不必从外部网站发布和下载它。 您执行此操作的方式取决于您使用的浏览器。

Chrome

Chrome

  • Visit chrome://extensions/ in your Chrome browser

    在Chrome浏览器中访问chrome://extensions/

  • Click Load Unpacked

    单击Load Unpacked

  • Select the extension’s folder

    选择扩展程序的文件夹

Firefox

火狐浏览器

  • Visit about:debugging

    访问about:debugging

  • Click on Load Temporary Add-on

    单击Load Temporary Add-on

  • Select the manifest.json within the extension’s folder

    在扩展程序的文件夹中选择manifest.json

Debugging tip: to view the console, (for example to see errors), right click/control click on the web extension icon or popup and select inspect

调试提示 :要查看控制台(例如查看错误),请右键单击/控制单击Web扩展图标或弹出窗口,然后选择“ inspect

为浏览器扩展编写JavaScript (Writing JavaScript for your browser extension)

There are many JavaScript API’s that can be used in your browser extension. This post will focus on the tabs API.

浏览器扩展中可以使用许多JavaScript API。 这篇文章将重点介绍tabs API。

For more on web extension APIs, see JavaScript APIs — Mozilla | MDN.

有关 Web扩展API的更多信息,请参见JavaScript API。 MDN

A browser extension that includes a popup HTML page when the user clicks on the icon in the browser’s toolbar could have a project structure like this:

当用户单击浏览器工具栏中的图标时,包含弹出HTML页面的浏览器扩展可能具有如下项目结构:

extension├── css│   └── style.css├── js│   └── popup.js├── manifest.json└── popup.html

The popup.html page would then run the js/popup.js script at the bottom of the page. You would add your JavaScript here.

然后, popup.html页面将在页面底部运行js/popup.js脚本。 您将在此处添加JavaScript。

Note: other project structures could have a folder for library code, as well as JavaScript files that run in other areas of the extension. For example, in the extension’s background scripts, and in any other documents bundled with the extension, including browser action or page action popups, sidebars, options pages, or new tab pages.

注意 :其他项目结构可能具有用于存储库代码的文件夹,以及在扩展的其他区域中运行JavaScript文件。 例如,在扩展程序的后台脚本中 ,以及在与扩展程序捆绑在一起的任何其他文档中,包括浏览器操作页面操作弹出窗口, 侧边栏选项页面新标签页

浏览器标签API (Browser tab APIs)

When writing a web extension, you need to use the tabs API to interact with the tabs in the browser. You also need to request permission from the user to do this.

编写Web扩展程序时,需要使用tabs API与浏览器中的tabs交互。 您还需要请求用户的许可才能执行此操作。

请求访问选项卡的权限 (Requesting permissions to access tabs)

Permissions need to be set in manifest.json. When a user tries to install the extension, it will prompt the user to confirm that this action is allowed.

需要在manifest.json设置权限。 当用户尝试安装扩展程序时,它将提示用户确认是否允许该操作。

"permissions": [    "tabs"  ]
使用浏览器API查询标签 (Querying tabs with the browser API)

Browsers, such as Firefox, use the browser.tabs API to interact with the browser’s tabs. To request info about the window’s tabs, you use the query method, which returns a promise with an array of tabs.

浏览器(例如Firefox)使用browser.tabs API与浏览器的标签进行交互。 要请求有关窗口选项卡的信息,请使用query方法,该方法返回带有选项卡数组的promise。

browser.tabs.query(  queryInfo  // object)

Read more about browser.tabs.query at tabs.query() — Mozilla | MDN

tabs.query()上了解有关browser.tabs.query的更多信息— Mozilla | MDN

To request the active tab for the browser window, you would write the following JavaScript:

要请求浏览器窗口的活动标签,您需要编写以下JavaScript:

browser.tabs.query({active: true, currentWindow: true}) .then(logCurrentTabData)

To get the current tab, you retrieve the first tab from the returned array of tabs. Following this structure, you can get the data from the browser tab.

要获取当前选项卡,请从返回的选项卡数组中检索第一个选项卡。 按照这种结构,您可以从浏览器选项卡中获取数据。

const logCurrentTabData = (tabs) => {  currentTab = tabs[0]  console.log(currentTab.title);  console.log(currentTab.url);}

However, when you try to open the extension in Chrome…

但是,当您尝试在Chrome中打开扩展程序时…

使用Chrome浏览器API查询标签 (Querying tabs with the chrome API)

Chrome has its own API for tabs queries. This follows the syntax chrome.tabs → your query

Chrome浏览器具有自己的标签查询API。 这遵循语法chrome.tabs →您的查询

chrome.tabs.query(object queryInfo, function callback)

Read more about Chrome’s tabs API here: chrome.tabs — Google Chrome.

在此处详细了解Chrome的tabs API: chrome.tabs-Google Chrome

So to use this method call, you would write the following in your browser extension:

因此,要使用此方法调用,应在浏览器扩展中编写以下内容:

chrome.tabs.query(   {active: true, currentWindow: true},   (arrayOfTabs) => { logCurrentTabData(arrayOfTabs) });

合并标签查询 (Combining tab queries)

检测使用哪个API (Detect which API to use)

You can then include both types of browser queries in your extension by using a conditional statement to determine which one to use.

然后,您可以通过使用条件语句来确定要使用哪种浏览器查询,从而在扩展程序中包括两种类型的浏览器查询。

if(chrome) {  chrome.tabs.query(    {active: true, currentWindow: true},    (arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }  );} else {  browser.tabs.query({active: true, currentWindow: true})    .then(logCurrentTabData)}
为每种浏览器类型添加更多代码 (Adding more code for each browser type)

Within each side of the condition, you can then add other pieces of code that depend on the different APIs, for example to create new tabs.

然后,在条件的各个方面,您可以添加依赖于不同API的其他代码段,例如,创建新选项卡。

chrome.tabs.create()browser.tabs.create()

Here is the code with the extra methods added in that opens a link in a new tab.

这是添加了额外方法的代码,它们在新选项卡中打开链接。

if(chrome) {  chrome.tabs.query(    {active: true, currentWindow: true},    (arrayOfTabs) => { logCurrentTabData(arrayOfTabs) }    );  $('a').click( (event) => { chrome.tabs.create({url:event.target.href}) } )} else {  browser.tabs.query({active: true, currentWindow: true})    .then(logCurrentTabData)  $('a').click( (event) => { browser.tabs.create({url:event.target.href}) } )}

发布扩展 (Publishing your extension)

With this code in place, you can now interact with the current browser without having to write two or more different web extension projects. You can now package your extension and publish to multiple web stores with the same file!

有了此代码,您现在可以与当前浏览器进行交互,而不必编写两个或多个不同的Web扩展项目。 现在,您可以打包扩展程序并使用同一文件发布到多个网络商店!

从Medium阅读更多 (Read more from Medium)
ryanwhocodes阅读更多 (Read more from ryanwhocodes)

翻译自: https://www.freecodecamp.org/news/how-to-make-a-cross-browser-extension-using-javascript-and-browser-apis-355c001cebba/

javascript浏览器

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值