skip to Main Content

trying to inject html to website and activeat button
using the onclick function

const locetion = document.querySelector("#app > div:nth-child(1)"); // set the locetion on the website for the injection
var div = document.createElement('div'); 
div.innerHTML = '<input type="search" id="mySearch" placeholder="Search for something..">';

let btn = document.createElement("button");
btn.onclick = function () {
  alert("Button is clicked");

};
btn.innerHTML = "Save";
btn.setAttribute('id','123123')
locetion.append(div);
locetion.append(btn);

locetion.append(div); --> document.body.appendChild(div) work just fine

2

Answers


  1. With manifest v3, you need to declare the activeTab permission in your manifest file to access the document object of the active tab. Also, make sure to include this code in a content script that is injected into the website you want to modify. You can specify the website in the matches field of your manifest file.

    // Get the location on the website for the injection
    const location = document.querySelector("#app > div:nth-child(1)");
    
    // Create a div element and set its innerHTML to the HTML you want to inject
    const div = document.createElement('div');
    div.innerHTML = '';
    
    // Create a button element and set its onclick function and innerHTML
    const btn = document.createElement("button");
    btn.onclick = function() {
      alert("Button is clicked");
    };
    btn.innerHTML = "Save";
    btn.setAttribute('id', '123123');
    
    // Append the div and button elements to the location on the website
    location.append(div);
    location.append(btn);
    
    Login or Signup to reply.
  2. It’s possible that the locetion variable isn’t being set correctly, or there might be an issue with the selector you’re using to target the element. You can try using console.log(locetion) to see if it’s correctly selecting the element you want.

    Also, make sure that the script is running after the element has loaded on the page. You can wrap your code in a DOMContentLoaded event listener to ensure that the script runs after the page has fully loaded, like this:

        document.addEventListener("DOMContentLoaded", function(event) {
      const locetion = document.querySelector("#app > div:nth-child(1)"); 
      var div = document.createElement('div'); 
      div.innerHTML = '<input type="search" id="mySearch" placeholder="Search for something..">';
    
      let btn = document.createElement("button");
      btn.onclick = function () {
        alert("Button is clicked");
      };
      btn.innerHTML = "Save";
      btn.setAttribute('id','123123')
      locetion.append(div);
      locetion.append(btn);
    });
    

    Also, there’s a typo in locetion. It should be location.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search