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

Chrome扩展中全局变量的创建与跨脚本访问问题求助

问题:Chrome扩展中跨脚本共享全局变量失败

我能找到的相关资料都比较陈旧。我想在Chrome扩展的一个脚本里创建全局变量,在另一个脚本中访问它。扩展的核心功能是查找类名为"page-title"的HTML元素并返回其innerHTML,功能正常后会指定运行的URL范围。

我试过多种方法,参考过消息传递方案,但因为需求不同,出现了关联popup.html的错误:Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.。我试过该错误的解决方案,但已经7年没碰编码,不确定是否正确实现。

我还试过HTML注入法传递值,但不修改Manifest安全默认设置就无法生效,而且方法太繁琐,希望用更常规的方式。也试过在函数/类/if语句外声明变量并优先加载对应JS文件来创建全局变量,同样没成功。


Manifest

{
    "name": "P.P. to Sharepoint",
    "version": "1.0.0",
    "description": "Open P.P. client folder in sharepoint",
    "manifest_version": 3,
    "author": "Zach Morris",
    "action":{
        "default_popup": "popup.html",
        "default_title": "Open Sharepoint Folder"
    },
    "background": {
        "service_worker": "background.js"
    },
    "permissions": [
        "activeTab",
        "tabs",
        "scripting",
        "notifications"
    ],
    "content_scripts": [{
    "js": ["contentScript.js"],
    "matches": ["<all_urls>"]
    }]
}

我的popup.html非常简单,仅包含一个按钮,我按自认为必要的顺序引入了所有JS文件:

<script src="globalVariable.js"></script>
<script src="contentScript.js"></script>
<script src="popup.js"></script>
<script src="script.js"></script>
<script src="background.js"></script>

globalVariable.js

该文件用于初始化全局变量作为占位符,后续需要从页面HTML中提取客户端名称,在popup.js的按钮点击事件中用于API调用:

var clientInfo = {
    name: 'test name'
};

ContentScript.js

我仅在importScripts存在时运行此脚本,尝试从页面获取客户端名称,若未获取到则抛出错误提示:

if( 'function' === typeof importScripts) {
  importScripts('globalVariable.js');

   addEventListener('message', onMessage);

   function onMessage(e) { 
    
        if(b[0]) {
            clientInfo.name = b[0].innerHTML;
            alert(clientInfo.name + ' was assigned!');
        } else {
            alert('There is no client on this screen ' + 'b[0] is ' + b[0] + " clientInfo = " + clientInfo.name);
        };
    }; 
} else {
    console.log("Your stupid code didn't work. ");
}

该文件引入globalVariable.js以使用clientInfo,并为按钮添加点击事件调用background.js的逻辑:

if( 'function' === typeof importScripts) {
   importScripts('globalVariable.js');
   addEventListener('message', onMessage);

   function onMessage(e) { 
      const text = clientInfo.name;
      const notify = document.getElementById( 'myButton' );

      notify.addEventListener( 'click', () => {
        chrome.runtime.sendMessage( '', {
          type: 'notification',
          message: text });
        
      } );
   }    
}

background.js

我同样引入了globalVariable.js以使用全局变量,当前用通知测试,后续会替换为API调用:

if( 'function' === typeof importScripts) {
   importScripts('globalVariable.js');
   addEventListener('message', onMessage);

   function onMessage(e) { 
     // do some work here 
     chrome.runtime.onMessage.addListener( data => {
  if ( data.type === 'notification' ) {
          chrome.notifications.create(
              '',
              {
                  type: 'basic',
                  title: 'Notify!',
                  message: data.message || 'Notify!',
                  iconUrl: 'notify.png',
              }
          );
          console.log("sent notification");
  };

});
   }    
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 01:33:24