如何为 Edge 或 Chrome 制作扩展程序

2025-06-08

如何为 Edge 或 Chrome 制作扩展程序

图片描述
您是否曾经在网页浏览器上安装过扩展程序?广告拦截器、游戏、工具?几乎可以肯定,您一生中都会安装过网页浏览器扩展程序。扩展程序是向浏览器添加实用功能或进行个性化设置的绝佳方式。有时,您找不到所需的扩展程序,想自己制作一个,却不知如何操作。这就是我们将要讨论的内容。

你为什么要做一个?

开发扩展程序是个好主意,因为它可以发展成为一项重要的收入来源。扩展程序还可以作为你之前工作经验的证明,帮助你进入理想的大学或工作。在开发扩展程序的过程中,你可能会学习一门新的编程语言,如果你还没有学习过编程语言,这或许可以作为你的副业。说实话,这很容易做到。

入门

在开发扩展程序之前,您需要一个 IDE 或文件编辑器。它们将用于编辑扩展程序的文件。您还需要了解如何使用扩展程序,例如将其开发成游戏或天气应用。准备好开始开发后,请阅读以下内容。

Manifest.json

在开始开发扩展程序之前,您需要一个文件来指定扩展程序的详细信息。在清单文件中,您需要声明应用的名称、描述、版本、所需权限(如有使用)、所需外部资源(如有使用)等。创建清单文件是开发扩展程序最简单的步骤。manifest.json 文件的格式如下。

{
  "name": "Current Weather",
  "description": "Get the current weather from this small extension. This extension needs your location to get the weather for your area.",
  "version": "1.0",
  "manifest_version": 3,
  "action": {
    "default_popup": "index.html",
    "default_icon": "cwlogo.png"
  },
  "options_ui": {
    "page": "settings.html"
  },
  "permissions": [
          "geolocation",
          "notifications"
  ],
  "host_permissions": [
  "https://api.openweathermap.org/",
  "https://translate.google.com/"
  ],
  "commands": {
    "_execute_action": {
      "suggested_key": {
        "default": "Ctrl+Shift+F",
        "mac": "MacCtrl+Shift+F"
      },
      "description": "Opens index.html"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

这是我的一个扩展程序 Current Weather 的 manifest.json 文件,您可以点击此处在 Edge上下载。如您所见,它使用了外部源 api.openweathermap.org,并使用了地理定位等服务。它还有一个设置页面,但并非必需。您可以点击此处查看所有权限。

查看 manifest.json 文件,你会看到它包含一个图标和一个操作页面。图标是安装扩展程序后显示的那个小图片。操作页面是点击扩展程序时弹出的小页面。这两个页面就是扩展程序本身。

制作UI

这一步非常简单。弹出页面使用 HTML,HTML 可以使用其他来源。我的扩展程序使用 HTML,而 HTML 使用了 JavaScript。如果您不熟悉 HTML,请查看我的另一篇关于 HTML 的文章。首先,您需要创建 HTML 页面的布局,然后确保 HTML 文件的名称包含在 manifest.json 文件中,这样当您点击它时,它才能正常工作。我的 HTML 页面布局如下。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Current Weather</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="body">
    <table>
    <thead>
      <th>Tempature</th>
      <th>Humidity</th>
      <th>Description</th>
      <th>Icon</th>
    </thead>
    <tbody>
      <tr>
        <td id="temp"></td>
        <td id="humidity"></td>
        <td id="description"></td>
        <td id="icon" style="background-color: gray;"></td>
      </tr>
    </tbody>  
    </table>
    <table>
      <thead>
        <th>Min Temp</th>
        <th>Max Temp</th>
        <th>Windspeed | Degree</th>
        <th>Pressure</th>
      </thead>
      <tbody>
        <tr>
        <td id="mintemp"></td>
        <td id="maxtemp"></td>
        <td id="wspdg"></td>  
        <td id="pressure"></td>
        </tr>
      </tbody>
    </table>
    <center><div id="result" style="font-size: 20px;"></div>
    <div id="google_translate_element"></div>
    </center>
    </div>
    <script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    <script src="script.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

如您所见,我使用一个 JavaScript 文件从 api.openweathermap.org 获取天气数据。我设置的 HTML 页面包含一个天气数据表。该 JavaScript 文件使用了 HTML 页面中的资源。接下来我们将进入下一节。

后端

现在你已经拥有了一个漂亮又炫酷的 UI,接下来需要为它创建一个不那么吸引人的文件。创建一个名为 script.js 的文件,并确保它与其他文件位于同一目录。现在,按照你希望应用运行的方式编写 js 文件,然后将其链接到 HTML 文件,这样就可以开始使用 HTML 了。我的扩展程序的后端如下所示。

 function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
}
  navigator.geolocation.getCurrentPosition(function(position) {

        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        const altitude = position.coords.altitude;
        const accuracy = position.coords.accuracy;
        const altitudeAccuracy = position.coords.altitudeAccuracy;
        const heading = position.coords.height;
        const speed = position.coords.speed;
        const timestamp = position.timestamp;

        // work with this information however you'd like!
    });
   function locationSuccess(position) {
        const latitude = position.coords.latitude;
        const longitude = position.coords.longitude;
        const altitude = position.coords.altitude;
        const accuracy = position.coords.accuracy;
        const altitudeAccuracy = position.coords.altitudeAccuracy;
        const heading = position.coords.height;
        const speed = position.coords.speed;
        const timestamp = position.timestamp;
        getweather(latitude, longitude);
        // work with this information however you'd like!
    }

    function locationError(error) {
        const code = error.code;
        const message = error.message;
        // read the code and message and decide how you want to handle this!
        document.getElementById('result').innerHTML = message;
    }

    navigator.geolocation.getCurrentPosition(locationSuccess, locationError);
function getweather(latitude, longitude){
const key = "6ea81243e055f1218d43cb862f1da44c";
const link = "https://api.openweathermap.org/data/2.5/weather?lat="+latitude+"&lon="+longitude+"&units=imperial&apikey="+key+"&lang="+localStorage.lang;
let request = new XMLHttpRequest();
request.open('GET', link);
request.responseType = 'json';
request.send();
request.onload = function() {
  const data = request.response;
  showweather(data)
}};
function showweather(obj) {
  var date = new Date(obj.dt * 1000);
// Hours part from the timestamp
var hours = date.getHours();
// Minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// Seconds part from the timestamp
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

  const weather = obj['weather'];
  var mt = obj.main.temp_min;
  for (let i = 0; i < weather.length; i++) {
    var icon = weather[i].icon;
    document.getElementById("temp").innerHTML = obj.main.temp+"&deg;F";
    document.getElementById("humidity").innerHTML = obj.main.humidity+"%";
    document.getElementById("description").innerHTML = weather[i].description;
    iconshow(icon,mt)
    document.getElementById("mintemp").innerHTML = mt+"&deg;F";
    document.getElementById("maxtemp").innerHTML = obj.main.temp_max+"&deg;F";
    document.getElementById("wspdg").innerHTML = obj.wind.speed+"MPH | "+obj.wind.deg+"&deg;";
    document.getElementById("pressure").innerHTML = obj.main.pressure;
  }
};
function iconshow(icon, mt) {
            var img = new Image();
            img.src = 
'https://openweathermap.org/img/wn/'+icon+'@2x.png';
            img.style.width = "20px";
            img.style.height = "20px";
            document.getElementById('icon').appendChild(img);
            if (mt>=85){
              document.getElementById("result").innerHTML="Its gonna be hot today. Bring some water wherever you go outside.";
              chrome.notifications.create('hotoutside', {
              type: 'basic',
              iconUrl: 'images/1.png',
              title: 'Test Message',
              message: 'You are awesome!',
              priority: 2
              });
            }else if(mt<=50){
              document.getElementById("result").innerHTML="Its going to be chilly today. Wear some warm clothes.";
            }
};
Enter fullscreen mode Exit fullscreen mode

它使用地理定位服务(需要权限)获取用户位置,从而获取其所在区域的天气信息。然后,它会使用 HTML 文件将天气信息显示在表格中供用户查看。如果您也想为您的扩展程序创建一个设置页面,请继续阅读。

制作设置页面

想让用户拥有一些选项吗?创建另一个 HTML 页面和 js 文件,并在清单文件中声明。您可以为用户提供更改颜色、语言等选项。我的代码如下。HTML

<!DOCTYPE html>
<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>Current Weather</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <div id="body">
      <center>
        <h1>Settings</h1>
        <p>View and set the settings for the current weather app.</p>
        <h2>Language</h2>
        <p>Set the extensions language to your preferance.</p>
        <select name="language" id="language">
          <option value="en" selected>English</option>
          <option value="de">German</option>
          <option value="sp">Spanish</option>
          <option value="ja">Japanese</option>
          <option value="fr">French</option>
        </select>
        <div id="currentlang"></div>
        <button id="submitlang">Set Language</button>
        <h2>Privacy</h2>
        <p>I will never share/sell you location or information to anybody because it is your information and only you shall decide what you would like to do with your privacy. If you decide that you do not want the extension to see your location anymore go to the three dots in the upper right corner, click more tools, click on details for the extension, disable location access. Please note that the extension does not work without location access.</p>
        <h3>Help/Support</h3>
        <p>If you are having problems with the extension then please go to the following site as it contains a forum with help and support. <a href="https://github.com/Grantrocks/Current-Weather/discussions" target="_blank">https://github.com/Grantrocks/Current-Weather/discussions</a>. That is the github discussion page contatining the files for the project and help and support for anyone that needs it.</p>
      </center>
      <div id="google_translate_element"></div>
    </div>
    <script type="text/javascript" src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
    <script src="settings.js"></script>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

JS:

function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
}
document.getElementById("submitlang").addEventListener("click", function(){
  var sellang = document.getElementById("language").value;
  var curl = document.getElementById("currentlang");
  if (sellang=="en"){
    curl.innerHTML = "English";
    localStorage.lang = "en";
  }else if(sellang=="de"){
    curl.innerHTML = "German";
    localStorage.lang = "de";
  }else if(sellang=="sp"){
    curl.innerHTML = "Spanish";
  }else if(sellang=="ja"){
    curl.innerHTML="Japanese";
  }else if(sellang=="fr"){
    curl.innerHTML="French";
  }else{
    curl.innerHTML="None Selected!";
  }
});

Enter fullscreen mode Exit fullscreen mode

你完成了

现在您的扩展程序已制作完成,您可以将其发布到您想要的地方。Google Chrome 网上应用店需要支付 5 美元的费用,Microsoft Edge 和 Firefox 均可免费发布,但如果您在这里发布,则需要稍微修改 manifest.json 文件,因为它使用的是 2.0 版本。
欢迎捐赠。
此外,我还使用了一个付费的链接缩短器,如果您也想使用它,请在此处注册。

鏂囩珷鏉ユ簮锛�https://dev.to/grantrocks/how-to-make-a-extension-for-edge-or-chrome-35ok
PREV
GraphQL Java 入门
NEXT
探索 Laravel 11 中的中间件