简体   繁体   English

如何动态 append 浏览器扩展中的内容脚本。?

[英]How to dynamically append the content script in browser extension.?

I am trying to append the script on content script from the API response.我正在尝试 append 来自 API 响应的内容脚本上的脚本。

Following is the content.js以下是 content.js

    locationHref = window.location.href;
    chrome.runtime.sendMessage({
        action: locationHref,
        value: false
    }, function (data) {
        localStorage();
        console.log('contetn js ', data);
    });

    function localStorage() {
        chrome.storage.local.get('script', (items) => {
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.innerHTML = items.script;
            document.body.appendChild(s);
            if (items.responseData) {
                setTimeout((r) => {

                    loadPopUp(items.responseData); // this method is not triggering

                }, 5000);
            }
        });
    }

And following is the background.js file以下是 background.js 文件

    chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
        fetchData(msg.action, sendResponse);
        return true;
    });


    function fetchData(url, sendResponse) {
        fetch("myscript.js", {
                method: 'GET',
            }).then(res => res.json())
            .then(response => {
                chrome.storage.local.set({
                    "script": response
                }, function () {});
                sendResponse(response);
            }).catch(error => {
                console.log(error)
            });
    }

And myscript.js has the following code. myscript.js 有以下代码。

function loadPopUp(data) {
        document.body.insertAdjacentHTML('beforeend', `<h4 style="color:white; font-size: 25px; text-align: center; margin-top: 15px;">
        ${data.name} has <span style="font-weight:bold">${data.count}</span> gene count</h4>`)
}

API response has the loadPopUp() method, after creating the script tag I am trying to call the loadPopup method but it is giving undefined error. API 响应具有 loadPopUp() 方法,在创建脚本标记后,我试图调用 loadPopup 方法,但它给出了undefined的错误。

How can I solve this problem.?我怎么解决这个问题。?

I have had success in embedded environments (ie, where I do not have access to the main page code) loading the scripts directly into the head.我在将脚本直接加载到头部的嵌入式环境(即,我无法访问主页代码)中取得了成功。

Here is what I do.这就是我所做的。

const exampleScript = {
   name: "p5.js",
   src: "https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js",
   id: "p5-script"
};

const loadScript = (scriptToLoad, callback) => {
    let script = document.createElement("script");
    script.src = scriptToLoad.src;
    script.id = scriptToLoad.id;
    script.onload = () => { 
        callback();
    }
    script.onerror = (e) => console.error("error loading" +  scriptToLoad.name + "script", e);
    document.head.append(script);
}

loadScript(exampleScript, () => {
   //...whatever you do after loading the script
});

The issue you are likely having is that you load it into the body instead of into the head.您可能遇到的问题是将其加载到身体而不是头部。

Here is an article that explains it.这是一篇解释它的文章。 https://aaronsmith.online/easily-load-an-external-script-using-javascript/ https://aaronsmith.online/easy-load-an-external-script-using-javascript/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 火狐网络扩展。 访问内容脚本中的弹出内容 - Firefox Web extension. Accessing popup content in content script Firefox扩展。 如何从控制台访问“浏览器”名称空间? - Firefox extension. How to access “browser” namespace from console? 当我在firefox扩展中使用page-mod添加contentscript时。 内容脚本功能执行三次 - When i add contentscript using page-mod in firefox extension. The content script functions are executed thrice 页面动态加载Chrome扩展程序内容时如何运行脚本 - How to run script when page loads content dynamically for Chrome Extension 在chrome扩展程序中,如何侦听由内容脚本动态生成的页面的事件? - In chrome extension, how to listen for events for a page that is dynamically generated by the content script? 如何:将Google Ajax API动态加载到Chrome扩展内容脚本中 - how to: dynamically load google ajax api into chrome extension content script FireFox扩展。 如何将叠加层添加到窗口的内容区域 - FireFox extension. How i can add overlay into content area of window firefox扩展。 如何捕获onload事件? - firefox extension. How to catch onload event? Firefox缓存我的扩展程序。 如何避免呢? - Firefox caching my extension. How to avoid it? chrome扩展插入内容脚本在浏览器操作上 - chrome extension insert content script on browser action
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM