I've been trying for hours and I can't get this working. I've written a content script that executes when the user loads a page. The click() method just simply won't work when I try click an element. I've tried multiple ways and it always works from the console, but not when I load the page.
The element I want to click:
<a id="startButton" href="javascript: popupHand.showPopup('popupLoginV2','loginHand.init()','','',true);" class="buttonGreen1 buttonSize1">Megpörgetem</a>
manifest.json - content script part
{
"content_scripts": [
{
"matches": ["*://*.bonuszbrigad.hu/bonuszkerek"],
"js": ["plugin/jquery-3.2.0.min.js", "js/page_wheel.js"],
"run_at": "document_end"
}
],
}
page_wheel.js
function spinWheel() {
var spinButton = $("#startButton");
if (spinButton.text() === "Már pörgettél") {
return "wait";
}
else if (spinButton.text() === "Megpörgetem") {
console.log("spin is available");
spinButton.on("click",
function () {
console.log("inside click action");
var popupLogin = $("#popup_login");
console.log(popupLogin);
if (popupLogin === null) {
return "login"
} else {
return "success";
}
}
);
spinButton.trigger("click");
}
}
When I load the page, the console logs show that it managed to enter
But there weren't any actual clicks made on the website. When I test the click method in the console, both of the below solutions work:
Also I see the same console logs - when executing click method from the console - but this way it's actually working.
Does anyone have an idea what is the problem? :/
I got this problem. In my case, I realized that there were HTML DOM and script load synchronizes. So when you call the click event, it was still fulfill loaded. So I added the script that invokes the click event into the window.load and it worked.
My script looks like below:
window.onload = function () {
const btn = document.getElementById('J_LinkBuy')
if (btn !== null) {
btn.dispatchEvent(new MouseEvent('click'))
}
}
Solution 1: You can use onclick attribute on any HTML tag and use it to call JavaScript functions.
<a onclick="sayHi('Hi')"> Click me </a>
<script>function sayHi(message){alert(message)}</script>
Solution 2: Use jquery click event function.
Remember, the jquery click should be called only after the target html element is generated. the click call won't work or else
$(css_selector).click();