onclick 无法正常工作 chrome expention JS HTML dom

问题描述 投票:0回答:2

尝试将 html 注入网站和 activeat 按钮 使用 onclick 函数

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
javascript html dom google-chrome-extension
2个回答
0
投票

使用清单 v3,您需要在清单文件中声明

activeTab
权限才能访问活动选项卡的
document
对象。此外,请确保将此代码包含在注入到您要修改的网站中的内容脚本中。您可以在清单文件的
matches
字段中指定网站。

// 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);

0
投票

locetion 变量可能未正确设置,或者您用于定位元素的选择器可能存在问题。您可以尝试使用 console.log(locetion) 来查看它是否正确选择了您想要的元素。

此外,确保脚本在元素加载到页面后运行。您可以将代码包装在 DOMContentLoaded 事件侦听器中,以确保脚本在页面完全加载后运行,如下所示:

    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);
});

另外,位置有错别字。它应该是位置。

© www.soinside.com 2019 - 2024. All rights reserved.