+
95
-

回答

编写一个Chrome插件来自动输入用户名和密码登录网站需要一些基本的HTML、CSS、JavaScript知识,以及对Chrome插件API的了解。以下是一个简单的示例,展示如何实现这一功能。

1. 创建插件目录和文件

首先,创建一个新的文件夹来存放插件文件。在这个文件夹中,创建以下文件:

manifest.jsonbackground.jscontent.jspopup.htmlpopup.js2. 编写 manifest.json

manifest.json 是Chrome插件的配置文件,定义了插件的基本信息和权限。

{
  "manifest_version": 3,
  "name": "Auto Login",
  "version": "1.0",
  "description": "Automatically fill in username and password to login",
  "permissions": [
    "activeTab",
    "scripting"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_popup": "popup.html",
    "default_icon": {
      "16": "icons/icon16.png",
      "48": "icons/icon48.png",
      "128": "icons/icon128.png"
    }
  },
  "icons": {
    "16": "icons/icon16.png",
    "48": "icons/icon48.png",
    "128": "icons/icon128.png"
  }
}
3. 编写 background.js

background.js 是后台脚本,用于处理插件的一些后台逻辑。

chrome.runtime.onInstalled.addListener(() => {
  console.log('Auto Login extension installed');
});
4. 编写 content.js

content.js 是内容脚本,用于在网页上下文中执行代码。

function autoFillLogin(username, password) {
  const usernameField = document.querySelector('input[name="username"]');
  const passwordField = document.querySelector('input[name="password"]');
  const loginButton = document.querySelector('button[type="submit"]');

  if (usernameField && passwordField && loginButton) {
    usernameField.value = username;
    passwordField.value = password;
    loginButton.click();
  } else {
    console.log('Username or password field not found');
  }
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "autoFillLogin") {
    autoFillLogin(request.username, request.password);
  }
});
5. 编写 popup.html

popup.html 是插件的弹出窗口页面。

<!DOCTYPE html>
<html>
<head>
  <title>Auto Login</title>
  <style>
    body {
      width: 200px;
      padding: 10px;
    }
    input {
      width: 100%;
      margin-bottom: 10px;
    }
    button {
      width: 100%;
    }
  </style>
</head>
<body>
  <input type="text" id="username" placeholder="Username">
  <input type="password" id="password" placeholder="Password">
  <button id="loginButton">Login</button>
  <script src="popup.js"></script>
</body>
</html>
6. 编写 popup.js

popup.js 是弹出窗口页面的脚本。

document.getElementById('loginButton').addEventListener('click', () => {
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  chrome.tabs.query({active: true, currentWindow: true}, (tabs) => {
    chrome.scripting.executeScript({
      target: {tabId: tabs[0].id},
      files: ['content.js']
    }, () => {
      chrome.tabs.sendMessage(tabs[0].id, {action: "autoFillLogin", username: username, password: password});
    });
  });
});
7. 加载插件打开Chrome浏览器,输入 chrome://extensions/ 进入扩展程序页面。打开右上角的“开发者模式”开关。点击“加载已解压的扩展程序”,选择你创建的插件文件夹。

现在,当你点击插件图标时,会弹出一个窗口,输入用户名和密码后点击“Login”按钮,插件会自动填充并提交登录表单。

请注意,自动填充用户名和密码可能会涉及到安全和隐私问题,确保你只在可信的环境中使用此功能。

网友回复

我知道答案,我要回答