Inject javascript into a website with a button - chrome extension

Hi, I was trying to make a chrome extension which injects code into a website when a inject button is pressed. I don’t know how to run code on the website, only the popup for my extension. Help is greatly appreciated.

https://developer.chrome.com/docs/extensions/reference/api/scripting

Hi, thanks for your response, I have used this code and I have gotten 0 errors - I’m not sure why nothing has happened; looking into it.

Update: I’ve figured out it’s something to do with the method of getting tabs, I’m trying to find out how I can get the tab id.

https://developer.chrome.com/docs/extensions/reference/api/tabs

(Probably most relevant sublink: https://developer.chrome.com/docs/extensions/reference/api/tabs#messaging )

Thanks, I’m still getting 2 errors from my extension:
Error handling response: TypeError: Error in invocation of scripting.executeScript(scripting.ScriptInjection injection, optional function callback): Error at parameter 'injection': Error at property 'target': Error at property 'tabId': Invalid type: expected integer, found object.
and for my function:

TypeError: Cannot read properties of undefined (reading 'id')
    at getCurrentTab

A Tab is an object with a property ‘id’.

Yes, I don’t understand where I have gone wrong I can send my code inside of my background.js file:

async function getCurrentTab() {
    let queryOptions = { active: true, lastFocusedWindow: true };
    let [tab] = await chrome.tabs.query(queryOptions);
    return tab.id;
}

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('Message received in background script:', message);
    if (message.action === "print") {
        console.log('run a', message);
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            var currTab = Number(getCurrentTab());
            console.log('run b', message);
            chrome.scripting.executeScript({
                target: { tabId: currTab },
                files: ["do_print.js"],
            }).then(() => console.log("script injected"));
        });
    }
});

Thanks for the help but I fixed it with:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
    console.log('Message received in background script:', message);
    if (message.action === "print") {
        chrome.tabs.query({ active: true }, function (tabs) {
            let tab = tabs[0];
            chrome.scripting.executeScript(
                {
                    target: { tabId: tab.id },
                    function: printHello,
                },
            );
        });
    }
});
1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.