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

如何从Django向Chrome扩展的JavaScript传递数据?附代码示例

Got it, let's walk through this step by step—you can absolutely pass data from Django to your Chrome extension's JavaScript, and we'll cover all your questions with concrete code examples. The core approach is using a simple REST API endpoint in Django that returns JSON data, which your extension's JavaScript can fetch and process.

1. Django Backend Setup (views.py + urls.py)

First, we'll create a Django view that pulls data from your MySQL database and returns it as JSON. We'll also include support for specifying a JavaScript method name in the response, since you asked about that.

views.py

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
# Import your Django model here to fetch real data from MySQL
# from .models import UserData

@csrf_exempt  # Disable CSRF for development (configure CORS properly in production)
def extension_data(request):
    # Fetch real data from MySQL using your model
    # db_data = UserData.objects.filter(user_id=request.user.id).values()[0]
    
    # For demonstration, we'll use mock data
    db_data = {
        "username": "john_doe",
        "saved_items": ["project report", "shopping list", "todo notes"],
        "preferences": {"theme": "dark", "notifications": True}
    }

    # Include the JavaScript method name you want to trigger in the response
    response_payload = {
        "target_method": "renderPopupContent",  # This is the JS method we'll define later
        "data": db_data
    }

    return JsonResponse(response_payload)

urls.py (map the view to a URL)

Add this to your app's urls.py so the extension can reach the endpoint:

from django.urls import path
from . import views

urlpatterns = [
    # Your other URLs...
    path('api/extension-data/', views.extension_data, name='extension_data'),
]

Important: Handle Cross-Origin Requests

Since your Chrome extension runs in a separate context from Django, you'll need to enable CORS (Cross-Origin Resource Sharing). Install django-cors-headers:

pip install django-cors-headers

Then update your settings.py:

INSTALLED_APPS = [
    # ...
    'corsheaders',
]

MIDDLEWARE = [
    # ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

# Allow your extension's origin (or use CORS_ALLOW_ALL_ORIGINS=True for development)
CORS_ALLOWED_ORIGINS = [
    "chrome-extension://your-extension-id-here",
    "http://localhost:8000",  # For local testing
]

2. Chrome Extension Frontend (popup.js + popup.html)

Now we'll write the JavaScript to fetch data from Django, handle the response, and call the method specified by the Django view.

document.addEventListener('DOMContentLoaded', () => {
    // Fetch data from your Django endpoint
    fetch('http://localhost:8000/api/extension-data/')  // Replace with your Django server URL
        .then(response => {
            if (!response.ok) throw new Error('Failed to fetch data');
            return response.json();
        })
        .then(response => {
            // Check if the specified method exists in our JS code
            if (typeof window[response.target_method] === 'function') {
                // Call the method with the received data
                window[response.target_method](response.data);
            } else {
                console.error(`Method ${response.target_method} not defined in popup.js`);
            }
        })
        .catch(error => {
            console.error('Error fetching data:', error);
        });
});

// Define the method specified in Django's response
function renderPopupContent(data) {
    // Update the popup UI with the received data
    const welcomeMsg = document.getElementById('welcome-msg');
    const savedItemsList = document.getElementById('saved-items');
    const themeToggle = document.getElementById('theme-toggle');

    // Populate welcome message
    welcomeMsg.textContent = `Hi, ${data.username}!`;

    // Populate saved items list
    savedItemsList.innerHTML = '';
    data.saved_items.forEach(item => {
        const li = document.createElement('li');
        li.textContent = item;
        savedItemsList.appendChild(li);
    });

    // Apply theme preference
    if (data.preferences.theme === 'dark') {
        document.body.classList.add('dark-theme');
        themeToggle.checked = true;
    }
}

Create a simple popup UI to display the data:

<!DOCTYPE html>
<html>
<head>
    <title>My Extension</title>
    <style>
        body { width: 250px; padding: 15px; }
        .dark-theme { background-color: #2d2d2d; color: #fff; }
        ul { padding-left: 20px; }
    </style>
</head>
<body>
    <h3 id="welcome-msg"></h3>
    <p>Saved Items:</p>
    <ul id="saved-items"></ul>
    <label>
        Dark Theme: <input type="checkbox" id="theme-toggle">
    </label>
    <script src="popup.js"></script>
</body>
</html>

manifest.json (Add Permissions)

Make sure your extension's manifest allows requests to your Django server:

{
    "manifest_version": 3,
    "name": "My Data Extension",
    "version": "1.0",
    "action": {
        "default_popup": "popup.html"
    },
    "host_permissions": [
        "http://localhost:8000/*"  // Replace with your Django server URL
    ]
}

Answering Your Specific Questions

  1. How to send data from a Django view?
    Use Django's JsonResponse class to return JSON-formatted data. This automatically sets the correct Content-Type header for JavaScript to parse. You can pass any JSON-serializable Python object (dictionaries, lists, etc.) as the response body.

  2. How to receive data in JavaScript?
    Use the modern fetch API to send an HTTP request to your Django endpoint. Parse the response as JSON, then use the data to update your popup's UI. For older browsers, you could use XMLHttpRequest, but fetch is cleaner.

  3. Can I define a JavaScript method name in a Django view?
    Absolutely! As shown in the examples, you can include a field like target_method in your JSON response. Then in your JavaScript, check if that method exists and call it with the payload. This is a flexible way to trigger different UI behaviors based on the data Django sends.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:24:05