mkHun
mkHun

Reputation: 5927

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

I am trying to append the script on content script from the API response.

Following is the 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

    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.

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.

How can I solve this problem.?

Upvotes: 3

Views: 1134

Answers (1)

Jos&#233; Mancharo
Jos&#233; Mancharo

Reputation: 336

I have had success in embedded environments (i.e., 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/

Upvotes: 1

Related Questions