You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Chrome扩展计算源文档哈希咨询:能否在JS执行前计算文档哈希?

Can a Chrome Extension Calculate Hashes of Open Documents (and Before Page JS Runs)?

Great question—let’s break this down into two clear scenarios since you’re asking about two distinct use cases.

1. Calculating the Hash of an Already Open Document

Absolutely, this is straightforward with Chrome Extension content scripts. Here’s how you’d approach it:

  • First, register a content script in your manifest.json that matches the pages you want to target (use <all_urls> if you need it to work everywhere).
  • The content script can access the current page’s DOM, so you can grab the full HTML (or specific parts) and use the Web Crypto API to generate a hash.
  • You can trigger this calculation either automatically when the script loads, or on user action (like clicking your extension’s popup icon).

Example Content Script Code

// content.js
async function calculateDocumentHash() {
  // Get the full HTML of the page
  const pageContent = document.documentElement.outerHTML;
  // Encode the content to a Uint8Array
  const encoder = new TextEncoder();
  const data = encoder.encode(pageContent);
  // Generate SHA-256 hash
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  // Convert buffer to hex string
  const hashArray = Array.from(new Uint8Array(hashBuffer));
  const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
  
  console.log('Document SHA-256 Hash:', hashHex);
  // Send the hash back to your extension's background script or popup
  chrome.runtime.sendMessage({ type: 'HASH_RESULT', hash: hashHex });
}

// Run when the user clicks the extension icon (triggered from popup/background)
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === 'CALCULATE_HASH') {
    calculateDocumentHash().then(() => sendResponse({ success: true }));
    return true; // Keep port open for async response
  }
});

2. Calculating the Hash of a Document Before Page JS Runs

This is a bit trickier, but definitely possible—you just need to intercept the document before any client-side JavaScript can modify it. There are two reliable approaches:

Option A: Use webRequest API to Intercept the Raw Server Response

This is the most robust method because it grabs the exact HTML sent by the server, before the browser parses or executes any page JS. Here’s how:

  1. Add the required permissions to your manifest.json:

    {
      "permissions": ["webRequest", "webRequestBlocking", "<all_urls>"]
    }
    
  2. In your background script, listen for the onResponseStarted event (with responseBody: true to access the raw content):

    // background.js
    chrome.webRequest.onResponseStarted.addListener(
      async (details) => {
        // Only target main document requests (not scripts/styles/images)
        if (details.type !== 'main_frame') return;
        
        // Read the raw response body
        const responseBody = await chrome.webRequest.getResponseBody(details.requestId);
        if (!responseBody) return;
        
        // Convert ArrayBuffer to string (adjust encoding if needed)
        const decoder = new TextDecoder('utf-8');
        const rawHtml = decoder.decode(responseBody.body);
        
        // Calculate hash (same as before)
        const encoder = new TextEncoder();
        const data = encoder.encode(rawHtml);
        const hashBuffer = await crypto.subtle.digest('SHA-256', data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
        
        console.log('Raw Document Hash (Before JS):', hashHex);
        // Store or send this hash as needed
      },
      { urls: ["<all_urls>"] },
      ["responseBody"]
    );
    

Option B: Content Script with run_at: "document_start"

If you don’t need the absolute raw server response (just the DOM before page JS modifies it), you can use a content script set to run at document_start. This runs your script before the browser parses the DOM or executes any page JS, but note that the DOM will be incomplete at this point—you’ll need to wait for the DOMContentLoaded event to get the full document, but this still happens before most page JS runs (unless the page uses inline synchronous scripts).

Add this to your manifest.json:

{
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["early-content.js"],
      "run_at": "document_start"
    }
  ]
}

Then in early-content.js:

document.addEventListener('DOMContentLoaded', async () => {
  const pageContent = document.documentElement.outerHTML;
  // Calculate hash same as before...
});

Key Notes for Option B

  • This won’t capture any modifications made by inline synchronous scripts (since those run before DOMContentLoaded), so if you need the truly unmodified document, stick with the webRequest method.

Final Takeaways

  • Calculating hashes of already open documents is easy with content scripts.
  • To get the hash before page JS runs, use the webRequest API for the raw server response, or a document_start content script if inline JS modifications aren’t a concern.

内容的提问来源于stack exchange,提问作者k06a

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:07:32