Search code examples
javascriptgoogle-chromegoogle-chrome-extension

Chrome Extension: How to inject code code into a new window


So let's say I want to inject some code to create a button on a new window in chrome (The window itself is opened via the extension's popup.js). How would I go about doing this?


Solution

  • you can use functions such as documnet.body.appendChild() instead of console.log() in foreground.js after opening files with the names I gave their names and filling them in this way. You can add whatever you want to the page this way.

    background.js

    function as(a,b,c) {
           
         chrome.tabs.executeScript(null, {file: "foreground.js"});
            chrome.tabs.insertCSS(null,{file:'./style.css'})
            console.log(a,b,c+'asd')
    }
    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        as(tabId, changeInfo, tab);
    }); 

    foreground.js

    window.onload=()=>{
        console.log('ok')
    }

    manifest.json

    {
        "name": "plugin",
        "version": "1.0",
        "manifest_version":2,
        "background": {
            "scripts":["./background.js"]
        },
        "browser_action":{
            "default_popup":"popup.html"
        },
        "permissions":[
          "tabs",
            "https://*/*"
        ]
    }

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        
    </body>
    </html>

    style.css

    button{
        color:red;
    }