如何在Chrome扩展中实现HTML与Python交互以生成文本摘要
Since Chrome extensions run in a browser-based JavaScript environment, you can’t execute Python code directly within the extension. However, you can build a simple Flask API that your extension sends text to, retrieves the summary from, and displays to the user.
Step 1: Update Flask Code (Add API Endpoint & CORS Support)
This code creates a POST endpoint that accepts text, generates a summary, and returns it as JSON. We also add CORS to allow cross-origin requests from your extension.
from flask import Flask, request, jsonify from flask_cors import CORS import gensim from gensim.summarization import summarize app = Flask(__name__) CORS(app) # Allow requests from your Chrome extension @app.route('/summarize', methods=['POST']) def get_summary(): data = request.get_json() original_text = data.get('text', '') if not original_text: return jsonify({'error': 'No text provided'}), 400 try: summary_text = summarize(original_text) return jsonify({'summary': summary_text}) except Exception as e: return jsonify({'error': str(e)}), 500 if __name__ == '__main__': app.run(debug=True) # Run the server locally
Step 2: Update Extension HTML & Add JavaScript Logic
We’ll add a textarea (better for long input than a single-line input), a result display area, and JavaScript to handle button clicks and API requests.
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Text Summarizer</title> <style> body { width: 300px; padding: 15px; } textarea { width: 100%; height: 150px; margin-bottom: 10px; padding: 8px; box-sizing: border-box; } button { width: 100%; padding: 8px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } #summary-result { margin-top: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; } </style> </head> <body> <textarea placeholder="Paste your text here!"></textarea> <button type="button" id="button_summarize">Summarize!</button> <div id="summary-result"></div> <script> const summarizeBtn = document.getElementById('button_summarize'); const textInput = document.querySelector('textarea'); const resultDiv = document.getElementById('summary-result'); summarizeBtn.addEventListener('click', async () => { const text = textInput.value.trim(); if (!text) { resultDiv.textContent = 'Please enter some text first!'; return; } try { resultDiv.textContent = 'Generating summary...'; const response = await fetch('http://localhost:5000/summarize', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ text: text }) }); if (!response.ok) throw new Error('Failed to fetch summary'); const data = await response.json(); if (data.error) { resultDiv.textContent = `Error: ${data.error}`; } else { resultDiv.textContent = data.summary || 'No summary available (text may be too short).'; } } catch (error) { resultDiv.textContent = `Connection error: ${error.message}`; } }); </script> </body> </html>
Step 3: Create Extension Manifest File
All Chrome extensions require a manifest.json to define their properties:
{ "manifest_version": 3, "name": "Text Summarizer", "version": "1.0", "description": "Summarize text using a Python backend", "action": { "default_popup": "popup.html" }, "permissions": ["activeTab"] }
How to Use
- Install required Python packages:
pip install flask flask-cors gensim - Run the Flask server:
python your_app.py - Load the extension in Chrome: Go to
chrome://extensions/, enable Developer Mode, click "Load unpacked", and select the folder containing yourpopup.htmlandmanifest.json.
If you want a self-contained extension without backend dependencies, use a JavaScript summarization library. This approach runs entirely in the browser and works offline.
Updated Extension HTML
We’ll use textrank-js, a lightweight implementation of the TextRank algorithm:
<!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Text Summarizer</title> <style> body { width: 300px; padding: 15px; } textarea { width: 100%; height: 150px; margin-bottom: 10px; padding: 8px; box-sizing: border-box; } button { width: 100%; padding: 8px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer; } #summary-result { margin-top: 15px; padding: 10px; border: 1px solid #eee; border-radius: 4px; } </style> <!-- Include the textrank-js library --> <script src="https://cdn.jsdelivr.net/npm/textrank-js@1.0.3/dist/textrank.min.js"></script> </head> <body> <textarea placeholder="Paste your text here!"></textarea> <button type="button" id="button_summarize">Summarize!</button> <div id="summary-result"></div> <script> const summarizeBtn = document.getElementById('button_summarize'); const textInput = document.querySelector('textarea'); const resultDiv = document.getElementById('summary-result'); summarizeBtn.addEventListener('click', () => { const text = textInput.value.trim(); if (!text) { resultDiv.textContent = 'Please enter some text first!'; return; } try { const tr = new TextRank(); tr.analyze(text); // Get top 3 sentences as summary (adjust the number as needed) const summarySentences = tr.getTopSentences(3); const summaryText = summarySentences.join(' '); resultDiv.textContent = summaryText || 'No summary available (text may be too short).'; } catch (error) { resultDiv.textContent = `Error generating summary: ${error.message}`; } }); </script> </body> </html>
Use the same manifest.json from Solution 1. This extension works immediately after loading in Chrome—no server required.
Which Approach to Choose?
- Flask Backend: Use this if you want to leverage your existing Python/gensim code and need more advanced summarization capabilities.
- JavaScript Library: Choose this for a simple, self-contained extension with no backend setup required.
内容的提问来源于stack exchange,提问作者anarchistpotatolover

