问题
I am just trying to set up a simple chrome extension that will just click on an element once the extension button is clicked on.
I have researched this a bit, and I can't find a simple answer that says how to click, everyone else has very elaborate code that I can't understand and don't know if it's necessary or not. What I mean is, whenever I search for just "click" I find a question that is much more advanced than my level.
(I am about to make a lot of $ off of this extension, so please will you help a brother out ;)
Using what I have seen I have scraped together the code:
popup.js:
var evt = document.createEvent ("HTMLEvents");
evt.initEvent ("click", true, true);
document.getElementById('product-addtocart-button').dispatchEvent (evt);
manifest.Json:
{
"manifest_version": 2,
"name": "Shoe BOT",
"description": "This extension shows a Google Image search result for the current page",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"permissions": [
"activeTab",
"https://shop.adidas.ae/en/"
]
}
popup.html:
<!doctype html>
<!--
This page is shown when the extension button is clicked, because the
"browser_action" field in manifest.json contains the "default_popup" key with
value "popup.html".
-->
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
}
#status {
}
</style>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: https://developer.chrome.com/extensions/contentSecurityPolicy
-->
<script src="popup.js"></script>
</head>
<body>
<!--<div id="status"></div>
<img id="image-result" hidden>-->
</body>
</html>
回答1:
It is not clear why you are using document.createEvent(). That interface is deprecated. To create events, you should be using event constructors. However, for a generic click event on an HTML element, you can just use the click() method without having to actually construct the event.
A simple, complete Chrome extension which injects a content script to click the button with id="product-addtocart-button"
when you click on a browser_action
button would be:
background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
chrome.tabs.executeScript(tab.id,{
code: "document.getElementById('product-addtocart-button').click();"
});
});
manifest.json:
{
"description": "Click a button with ID=product-addtocart-button",
"manifest_version": 2,
"name": "click-product-addtocart-button",
"version": "0.1",
"permissions": [
"activeTab"
],
"background": {
"scripts": [
"background.js"
]
},
"browser_action": {
"default_icon": {
"32": "myIcon.png"
},
"default_title": "Click product-addtocart-button"
}
}
来源:https://stackoverflow.com/questions/40244252/how-to-click-on-a-button-in-chrome-extension