Chrome扩展:如何在注入脚本中调用Content Script方法或sendMessage?
Got it, let's break down how to fix this issue. The core problem here is context isolation—your injected script (running in the page's main world) and the content script (running in an isolated content world) don't share variables or functions directly. Here are two solid solutions:
Solution 1: Communicate via Custom DOM Events
Since both contexts share the same DOM, we can use custom events to pass data from the injected script to the content script.
Step 1: Update Your Content Script
Add an event listener to catch the custom event from the injected script, then handle the token data (either call your existing sendTokens function or send the message directly):
// Content Script code chrome.extension.sendMessage({ greetings: "hello from new page" }, function (response) { console.log("response", response) let storeData = response.store var readyStateCheckInterval = setInterval(function () { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); let th = document.getElementsByTagName('body')[0]; let injectSc = document.createElement('script'); let filePath = chrome.extension.getURL('src/inject/injectScript.js') injectSc.setAttribute('type', 'text/javascript'); injectSc.setAttribute('src', filePath); th.appendChild(injectSc); } },100) }) // Add this: Listen for custom events from the injected script document.addEventListener('passTokensToContent', (event) => { const userTokens = event.detail; // Either call your existing sendTokens function... sendTokens(userTokens); // ...or send the message directly here if you prefer }); function sendTokens(user_token){ chrome.extension.sendMessage(user_token, function (response) {}) }
Step 2: Modify the Injected Script
Instead of trying to call sendTokens directly, dispatch a custom event with your token data:
// injectScript.js code if (document.readyState === "complete" || document.readyState === "interactive"){ console.log("window from inject script",window); let yajRex = new RegExp('example.xyz.com') if(yajRex.test(window.location.href)){ let user_tokens= { token1:window.paramValue, token2:window.paramValue } console.log(user_tokens); // Dispatch custom event with token data const tokenEvent = new CustomEvent('passTokensToContent', { detail: user_tokens }); document.dispatchEvent(tokenEvent); } }
Solution 2: Send Messages Directly from the Injected Script
If your only goal is to send tokens to the extension's background script, you can skip the content script entirely and call chrome.runtime.sendMessage directly in the injected script—just make sure your extension has the right permissions.
Step 1: Update injectScript.js
// injectScript.js code if (document.readyState === "complete" || document.readyState === "interactive"){ console.log("window from inject script",window); let yajRex = new RegExp('example.xyz.com') if(yajRex.test(window.location.href)){ let user_tokens= { token1:window.paramValue, token2:window.paramValue } console.log(user_tokens); // Send message directly to extension background chrome.runtime.sendMessage(user_tokens, function(response) { console.log('Message received by extension:', response); }); } }
Step 2: Verify Permissions in manifest.json
Make sure your extension declares the necessary permissions to use chrome.runtime.sendMessage on the target site:
{ "permissions": ["activeTab", "scripting"], "host_permissions": ["*://example.xyz.com/*"] }
Which Solution to Choose?
- Use Solution 1 if you need the content script to process the token data before sending it to the background (e.g., adding extra context from the content script's store).
- Use Solution 2 for a more direct approach if you don't need any intermediate processing in the content script.
内容的提问来源于stack exchange,提问作者Aakruti beladiya




