【问题标题】:Get button clicked with chrome extension使用 chrome 扩展点击获取按钮
【发布时间】:2018-01-15 00:06:44
【问题描述】:

我想知道如何检测是否在带有我的 chrome 扩展程序的网页上单击了具有特定 id 的按钮。 使用我的代码时,我有一个错误说我的元素未定义。 这是我的清单:

{
"manifest_version": 2,

"name": "app",
"description": "my app",
"version": "1.0",

"browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html",
    "default_title": "Changer le background"
},
"permissions": [
    "activeTab",
    "storage"
]

}

还有我的 popup.js 文件:

document.addEventListener('DOMContentLoaded', () => {
getCurrentTabUrl((url) => {
    document.getElementById('mybutton').addEventListener('click', function() {
        var script = "console.log('clicked');";
        chrome.tabs.executeScript({code: script});
    });
});

});

【问题讨论】:

  • 你必须使用在网页上注入的content script
  • 你能给我举个例子吗?我正在阅读谷歌开发文档,但我不明白它如何解决我的问题!

标签: javascript google-chrome dom google-chrome-extension


【解决方案1】:

在用户自己单击扩展程序图标之前,您的 popup.js 将不会加载...我认为您应该改变您的方法并使用这样的内容脚本:

document.getElementById('mybutton').addEventListener('click', function() {
        console.log('clicked');
});

您需要更新 manifest.json 以使用内容脚本,例如:

"content_scripts": [
  {
    "matches": ["the url of a page for the script", "the url of another page"],
    "js": ["your_script.js"]
   }
   ],

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 2023-03-10
    • 2018-04-13
    • 2014-12-18
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多