rookiemaster
V2EX  ›  问与答

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

  •  
  •   rookiemaster · Jul 28, 2024 · 1854 views
    This topic created in 663 days ago, the information mentioned may be changed or developed.

    问了 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 replies    2024-07-29 18:22:29 +08:00
    AV1
        1
    AV1  
       Jul 29, 2024
    content_scripts 里 js 的顺序错了,调换一下就行了
    Immortal
        2
    Immortal  
       Jul 29, 2024
    应该是 1L 说的这样
    题外话,现在有不少插件框架,直接用省事很多,例如 wxt
    skuuhui
        3
    skuuhui  
       Jul 29, 2024
    manifest 中添加节点
    "web_accessible_resources": [
    {
    "matches": [
    "*://你的域名/*"
    ],
    "resources": [
    "myfunction.js"
    ]
    }
    ],
    rookiemaster
        4
    rookiemaster  
    OP
       Jul 29, 2024
    @DOLLOR 谢谢,已解决
    rookiemaster
        5
    rookiemaster  
    OP
       Jul 29, 2024
    @skuuhui 谢谢,已解决
    rookiemaster
        6
    rookiemaster  
    OP
       Jul 29, 2024
    @Immortal 原来还有框架,改天看看
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2841 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 14:55 · PVG 22:55 · LAX 07:55 · JFK 10:55
    ♥ Do have faith in what you're doing.