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

Chrome扩展:Popup与Content Script间变量共享问题求助

Solution: Passing Array from Popup to Content Script in Chrome Extension

Hey there! Let's tackle this Chrome Extension issue you're having—passing that array from your Popup to the Content Script isn't as straightforward as sharing a global variable because they run in entirely separate JavaScript contexts. Your previous attempts with global variables or nested functions won't work for this reason, but don't worry—Chrome provides built-in tools to fix this. Here are two reliable solutions:

1. Use Runtime Message Passing (Instant Data Transfer)

This is perfect if you need to send the data immediately after the user submits the form.

Step 1: Modify Your Popup's loopTheArray Function

Update the function to send the array to the active tab's Content Script using chrome.runtime.sendMessage:

function loopTheArray(){
  var responseObject = document.getElementById('code').innerHTML;
  var responseParsed = JSON.parse(responseObject);
  var responseValues = Object.values(responseParsed);

  // Get the currently active tab and send the data
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
    chrome.tabs.sendMessage(tabs[0].id, {userSelections: responseValues}, function(response) {
      console.log('Data sent to Content Script:', response.status);
    });
  });
}

Step 2: Add a Message Listener in Your Content Script

Create a listener to receive the data and run your scanning/injection logic:

// content.js (your Content Script file)
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.userSelections) {
    const userChoices = request.userSelections;
    // Run your div scanning and HTML injection here
    scanAndInjectContent(userChoices);
    sendResponse({status: 'Data received successfully'});
  }
});

function scanAndInjectContent(values) {
  console.log('Received selections from Popup:', values);
  // Example logic: Find divs matching each value and inject HTML
  values.forEach(value => {
    const matchingDivs = document.querySelectorAll(`div:contains('${value}')`);
    matchingDivs.forEach(div => {
      const injectedHTML = `<span class="highlight-tag">Matched: ${value}</span>`;
      div.insertAdjacentHTML('beforeend', injectedHTML);
    });
  });
}

Step 3: Verify Manifest.json Configuration

Make sure your Content Script is properly declared in manifest.json (adjust the matches value to target your desired URLs):

"content_scripts": [
  {
    "matches": ["<all_urls>"], // Or specific URLs like "https://example.com/*"
    "js": ["content.js"]
  }
]

2. Use Chrome Local Storage (Persistent Data)

If you need to store the user's selections for later use (or if the Content Script might need to access it after the Popup closes), use Chrome's local storage API.

Step 1: Save Data to Storage in Popup

function loopTheArray(){
  var responseObject = document.getElementById('code').innerHTML;
  var responseParsed = JSON.parse(responseObject);
  var responseValues = Object.values(responseParsed);

  // Save the array to Chrome's local storage
  chrome.storage.local.set({savedSelections: responseValues}, function() {
    console.log('Selections saved to storage');
    // Optional: Notify Content Script to fetch the data
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, {action: 'loadSavedData'});
    });
  });
}

Step 2: Retrieve Data in Content Script

// content.js
// Option 1: Listen for a trigger from the Popup
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === 'loadSavedData') {
    fetchAndUseSavedData();
  }
});

// Option 2: Load data automatically when the Content Script starts
fetchAndUseSavedData();

function fetchAndUseSavedData() {
  chrome.storage.local.get('savedSelections', function(result) {
    const savedValues = result.savedSelections;
    if (savedValues) {
      scanAndInjectContent(savedValues);
    }
  });
}

function scanAndInjectContent(values) {
  // Same injection logic as the first solution
  console.log('Loaded selections from storage:', values);
}

Important Note for Storage

Don't forget to add the storage permission in your manifest.json:

"permissions": ["storage", "tabs"]

Why Your Previous Attempts Failed

Popup pages and Content Scripts run in isolated contexts—their global variables don't overlap at all. When you tried setting a global variable, it only existed in the Popup's context, so the Content Script had no way to access it. Chrome's messaging and storage APIs are designed specifically to bridge this gap.

Since you're new to JavaScript and Chrome Extensions, it's totally normal to hit this hurdle—this is a common pain point for beginners. Take your time testing these solutions, and feel free to tweak the logic to fit your exact project needs!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:50:47