以下是一个简单的 Chrome 扩展程序,可以实现您的需求:

  1. 创建一个名为'manifest.json'的文件,并将以下代码复制到其中:
{
  "manifest_version": 2,
  "name": "谷歌搜索",
  "version": "1.0",

  "permissions": [
    "tabs",
    "activeTab",
    "downloads"
  ],

  "browser_action": {
    "default_title": "搜索谷歌",
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  }
}
  1. 创建一个名为'popup.html'的文件,并将以下代码复制到其中:
<!DOCTYPE html>
<html>
<head>
  <title>谷歌搜索</title>
  <script src="popup.js"></script>
</head>
<body>
  <button id="searchBtn">搜索</button>
</body>
</html>
  1. 创建一个名为'popup.js'的文件,并将以下代码复制到其中:
document.addEventListener("DOMContentLoaded", function() {
  var searchBtn = document.getElementById("searchBtn");
  searchBtn.addEventListener("click", function() {
    chrome.tabs.create({url: "https://www.google.com/"}, function(tab) {
      chrome.tabs.executeScript(tab.id, {code: 'chrome.runtime.sendMessage({action: "saveHtml"}); document.querySelector("input[name=q]").focus();'});
    });
  });
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action == "saveHtml") {
    chrome.tabs.executeScript({code: 'var html = document.documentElement.innerHTML; chrome.runtime.sendMessage({action: "downloadHtml", html: html});'});
  }
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action == "downloadHtml") {
    var blob = new Blob([request.html], {type: "text/html"});
    chrome.downloads.download({url: URL.createObjectURL(blob), filename: "google.html"});
  }
});
  1. 在扩展程序管理页面中,选择'加载已解压的扩展程序',并选择包含上述三个文件的文件夹。

  2. 点击扩展程序图标,将打开一个新的谷歌搜索页面。点击'搜索'按钮,将保存该页面的HTML到本地,并在搜索框中输入焦点。

请注意,该扩展程序仅限于对谷歌搜索页面的操作,不适用于其他网站。此外,由于Chrome的安全策略,无法直接从内容脚本中访问本地文件系统,因此需要使用background脚本作为中介来实现HTML的保存。

Chrome 扩展:一键访问谷歌搜索并保存页面 HTML

原文地址: https://www.cveoy.top/t/topic/n7S2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录