Frontend Development 8 min read

Building a Chrome Extension with Python and Flask for JSON Format Validation

This article provides a step‑by‑step guide to creating a Google Chrome extension using Python and Flask that validates JSON data on the current page, covering prerequisite setup, project structure, manifest configuration, content and background scripts, backend server implementation, and testing procedures.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Building a Chrome Extension with Python and Flask for JSON Format Validation

In web development, JSON is a common data format, and validating its structure is often needed. This guide explains how to build a Google Chrome extension with Python that checks JSON format on the current page, improving development efficiency.

Project Overview : The extension consists of a Chrome extension front‑end and a Flask back‑end server that validates JSON using jsonschema.

Prerequisites : Install Python, Google Chrome, and the required libraries Flask and Flask‑CORS.

Project Structure :

- chrome_extension/
  - manifest.json
  - content_script.js
  - background.js
- server/
  - app.py

Chrome Extension Implementation :

manifest.json defines the extension name, version, permissions, and points to the back‑end server at http://localhost:5000/* :

{
  "manifest_version": 2,
  "name": "JSON格式检验插件",
  "version": "1.0",
  "permissions": ["activeTab", "http://localhost:5000/*"],
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["content_script.js"]
    }
  ],
  "icons": {
    "16": "icon_16.png",
    "48": "icon_48.png",
    "128": "icon_128.png"
  }
}

content_script.js listens for a message with action validateJson , sends the JSON data to the back‑end via a POST request, and returns the validation result:

// 监听消息事件
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'validateJson') {
    var jsonData = request.jsonData;
    fetch('http://localhost:5000/validate', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(jsonData)
    })
    .then(function(response) {
      return response.json();
    })
    .then(function(data) {
      sendResponse(data);
    })
    .catch(function(error) {
      sendResponse({ error: error.message });
    });
    return true;
  }
});

background.js injects content_script.js into every loaded page:

// 监听页面加载事件
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
  if (changeInfo.status === 'complete') {
    // 注入内容脚本
    chrome.tabs.executeScript(tabId, { file: 'content_script.js' });
  }
});

Backend Server Implementation :

app.py creates a Flask application with CORS support and defines a /validate endpoint that uses jsonschema to check the incoming JSON data:

from flask import Flask, request, jsonify
from flask_cors import CORS
import jsonschema

app = Flask(__name__)
CORS(app)

@app.route('/validate', methods=['POST'])
def validate():
  try:
    data = request.get_json()
    jsonschema.validate(data, schema)
    return jsonify({ 'valid': True })
  except jsonschema.ValidationError as e:
    return jsonify({ 'valid': False, 'error': e.message })

if __name__ == '__main__':
  app.run()

Usage and Testing : After loading the extension in Chrome, visit a page containing JSON; the extension detects and sends the data to the Flask server. The server returns validation results, which the extension displays. The back‑end can also be tested directly with tools like Postman by POSTing JSON to http://localhost:5000/validate .

Conclusion : By following this tutorial, developers can create a Chrome extension that validates JSON format using a Python Flask back‑end, streamlining JSON checks during web development.

javascriptpythonFlaskjson validation
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.