V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
rookiemaster
V2EX  ›  问与答

开发 chrome 插件的时候,怎么在 content script 中引入其他的 js 文件?

  •  
  •   rookiemaster · 50 天前 · 954 次点击
    这是一个创建于 50 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问了 gpt ,使用了以下两个方法都没用:

    1. 动态加载 script 标签:
    function loadScript(url) {
        var script = document.createElement('script');
        script.src = url;
        script.type = 'text/javascript';
        document.head.appendChild(script);
    }
    
    // 调用函数加载其他 JavaScript 文件
    loadScript(chrome.runtime.getURL('path/to/your/other-script.js'));
    
    1. 在 manifest.json 中配置 module, 然后使用 export import:
    "content_scripts": [
            {
                "matches": ["<all_urls>"],
                "js": [
                    "content.js",
                    "myfunction.js"
                ],
                "type": "module"
            }
    ],
    

    myfunction.js:

    function hello() {
        console.log("Hello World")
    }
    

    content.js:

    hello()
    
    6 条回复    2024-07-29 18:22:29 +08:00
    DOLLOR
        1
    DOLLOR  
       50 天前
    content_scripts 里 js 的顺序错了,调换一下就行了
    Immortal
        2
    Immortal  
       49 天前
    应该是 1L 说的这样
    题外话,现在有不少插件框架,直接用省事很多,例如 wxt
    skuuhui
        3
    skuuhui  
       49 天前
    manifest 中添加节点
    "web_accessible_resources": [
    {
    "matches": [
    "*://你的域名/*"
    ],
    "resources": [
    "myfunction.js"
    ]
    }
    ],
    rookiemaster
        4
    rookiemaster  
    OP
       49 天前
    @DOLLOR 谢谢,已解决
    rookiemaster
        5
    rookiemaster  
    OP
       49 天前
    @skuuhui 谢谢,已解决
    rookiemaster
        6
    rookiemaster  
    OP
       49 天前
    @Immortal 原来还有框架,改天看看
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   992 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 19:07 · PVG 03:07 · LAX 12:07 · JFK 15:07
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.