Get button clicked with chrome extension

折月煮酒 提交于 2019-12-13 02:49:13

问题


I want to know how to detect if a button with a certain id is clicked on a webpage with my chrome extension. With my code I have an error saying that my element is undefined. Here is my manifest :

{
"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"
]

}

And my popup.js file :

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

});


回答1:


your popup.js will not load until the user himself will click on the extension's icon... i think you should change your approach and use a content-script like this:

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

you'll need to update your manifest.json for using a content script, something like that:

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


来源:https://stackoverflow.com/questions/48246397/get-button-clicked-with-chrome-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!