I'm writing a userscript (javascript/jquery) to automate some things in a browser game. There's an auction where products can be bought with a discount. I want a script that automatically buys goods when it has 33% discount.
The script runs on the url of the auction (greasemonkey), then checks if there are products with at least 33% discount - if that's the case then it will press the button in that row to buy the product.
The problem I'm facing now is: Once you have pressed the button, you have to confirm you want to buy the goods via an alert box. Is there a way to automate this?
I've googled and also checked stackoverflow and people say it's not possible with javascript/jquery. Is this really the case? That would mean it's basically impossible to automate buying goods in the browser game i'm playing. I was thinking of letting the script automatically press ENTER because that would be the same as clicking 'Ok' in the alert box. But that also is impossible they say. So now i'm wondering: is there a way to automate this?
This is the code behind the button:
<input id="buybutton_3204781" class="button" type="button" onclick="if(confirm('Wil je deze producten kopen?')){document.submitForm.BuyAuctionNr.value=3204781; document.submitForm.submit();}{return false;}" value="Kopen">
EDIT:
Hooray, it works by changing the attribute onClick of the button!!
This is the code used:
$('element').attr('some attribute','some attributes value');
Can be closed now, thanks alot guys, appreciate your help!!
Depending on the browser, it may be possible to overwrite window.confirm such as
(function() {
'use strict';
// Might was well save this in case you need it later
var oldConfirm = window.confirm;
window.confirm = function (e) {
// TODO: could put additional logic in here if necessary
return true;
};
} ());
I didn't do any extensive testing, but I was able to override window.alert and window.confirm in firebug at the very least.
Note that this won't help you if their scripts have gained a reference to alert / confirm already (such as var a = window.confirm; a('herp');)
An alternate approach would be to override the function of the button you are auto clicking, or issue the AJAX / POST manually using some xhr.
With JavaScript, you have the ability to alter the HTML and JavaScript code in any way you like.
I would recommend altering the OnClick function so that
<input id="buybutton_3204781" class="button" type="button"
onclick="
if(confirm('Wil je deze producten kopen?'))
{
document.submitForm.BuyAuctionNr.value=3204781;
document.submitForm.submit();
}
{
return false;
}" value="Kopen">
simply becomes
<input id="buybutton_3204781" class="button" type="button"
onclick=
"document.submitForm.BuyAuctionNr.value=3204781;
document.submitForm.submit();"
value="Kopen">
Without changing much you can try this
$(".button").each(function() {
if (this.id.indexOf("buybutton")!=-1) this.onclick=function() {
document.submitForm.BuyAuctionNr.value=this.id.replace("buybutton_","");
document.submitForm.BuyAuctionNr.submit();
}
});
I use this and onclick because I want to replace the existing onclick handler, not add one
If you just want to buy, grab the IDs and submit the form with your user script
since i do not know how you know the discount, an example could be
$(".button").each(function() {
if (this.id.indexOf("buybutton")!=-1) {
var ID = this.id.replace("buybutton_","");
if ($("#discount_"+ID).val()<30) {
document.submitForm.BuyAuctionNr.value=ID;
document.submitForm.BuyAuctionNr.submit();
}
}
});
Which will submit the first it finds. Replace the submit with $.get or post to submit all the discounted stuff
You have to replace the original system alert by the jquery modal to achieve such requirement.
The following is a tutorial to introduce jquery modal:
http://www.jacklmoore.com/notes/jquery-modal-tutorial
Related
As part of my new job, I'm creating a small form where users answer a question and this is then saved and output at the end of the pages.
I started off with having a prompt where users were asked to explain their answers (which worked perfectly!), however I've been asked to change this to an input box.
Essentially the process I need to do is:
User enters in text box -> Clicks next button -> save input to session variable and move to next page
So far, I have the following HTML in the body:
<form name="next" action='#' method=post>
Explanation:<input type="text" id="xp" required><br>
<button class="nextButton" onclick="return explanation()">Next</button>
</form>
with the corresponding javascript:
function explanation() {
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
document.location.href = 'page2.html';
}
So far the result of this is:
The text box is cleared, but nothing is saved or displayed onscreen
The next page is not displayed.
Any help/advice would be appreciated. I'm relatively new to js so I'd be grateful! I'm well aware that there are similar questions around, I just can't seem to see where I'm going wrong.
#David is right. You can add event.preventDefault() function to prevent the form from its default behaviour, which is submitting. Otherwise your code seems to work.
function explanation() {
event.preventDefault(); // <-- add here
var exp = document.getElementById('xp').value;
sessionStorage.setItem("p1_reason", exp);
alert(exp);
window.location.href = 'page2.html';
}
Also, don't use document.location.href, it's deprecated. It's better to use window.location.href instead.
When you click on nextButton, the browser run explanation() and then try to execute the action of your form. Because your action is action='#' it just try to reload the page, preventing document.location.href for working properly.
Actually, you can try to don't enter nothing on the box and click on the button. The redirect will work because the form is empty, so there is nothing to submit.
I'm not sure how to do a pop-up that warns when you are clicking on external links, using javascript.
I figured that it would be handy to put a class on my external links as well, but I'm not quite sure it's done correct as it is now either. This is the HTML I'm using at the moment:
<div id="commercial-container">
<img src="picture1.jpg" />
<img src="pciture2.jpg" />
<img src="picture3.jpg" />
<img src="picture4" />
</div>
I'm very new to javascript and very unsure on how to solve my problems. The pretty much only thing I figured out so far is that I will have to use window.onbeforeload but I have no clue on how to figure out how to write the function I need.
I want to keep my javascript in a separated .js document instead of in the HTML as well.
Call the confirm() function from the onClick attribute. This function returns true if the user clicks OK, which will open the link, otherwise it will return false.
<img src="picture1.jpg"/>
Hope this helps.
You can do it by adding a click event handler to each link. This saves having to use a classname.
window.onunload will run even if the user is just trying to close your site, which you may not want.
staying in site
going external
<script>
var a = document.getElementsByTagName('a');
var b = a.length;
while(b--){
a[b].onclick = function(){
if(this.href.indexOf('yourwebsitedomain.com')<0){
//They have clicked an external domain
alert('going external');
}
else{
alert('staying in your site');
}
};
}
</script>
Since you're new to Javascript I advice you to use a javascript framework to do all the "heavy work" for you.
For example with JQuery you can easily bind an onClick event to all external links by doing:
$(".external").click(function(event) {
var confirmation = confirmation("Are you sure you want to leave ?");
if (!confirmation) {
// prevents the default event for the click
// which means that in this case it won't follow the link
event.preventDefault();
}
});
This way every time a user clicks on a link with the external class, a popup message box asking for a confirmation to leave will be prompt to the user and it will only follow the link if the user says "yes".
In case you want only to notify without taking any actions you can replace the confirmation by a simple alert call:
$(".external").click(function(event) {
alert("You are leaving the site");
});
If the user click an image,div,.. you need to look for the parent node. !There could be several elements wrapped with a-tag.
document.addEventListener('click',function(event){
var eT=(event.target||event.srcElement);
if((eT.tagName.toLowerCase()==='a' && eT.href.indexOf('<mydomain>')<0)
|| (eT.parentNode!==null && eT.parentNode.tagName.toLowerCase()==='a'
&& eT.parentNode.href.indexOf('<mydomay>')<0))
{
//do someting
}
else if(eT...){
...
}
},false);
Two side notes:
If you want to keep track a user by cookie or something similar, it's good practice to check external links, set a timeout and make a synchronic get request to renew.
It's better to add the event to the document or a div containing all events and decide on target.
I have a page where administrators can manage user accounts. This is done by clicking on an edit link next to the user's name on the main page (admin/usermanage/) which takes the administrator to the edit page for that user ID (admin/usermanage/?edit=x (where X is the user ID)).
On this page, there is a delete button which takes the user back to the main page that lists all the accounts.
function deleteaccount_confirmation() {
var answer = confirm("Are you sure you want to delete this account?")
if (answer){
window.location = "../usermanage/index.php";
}
}
This doesnt work though. The user stays on the same page with the URL unchanged (admin/usernamage/?edit=x)
Any possible solutions?
window.location.href = "../usermanage/index.php"
Try this
window.open('http://somefoler/yoursitename.php','','','_self');
This should work. I've tested. If doesn't spend a little time in google
Heres what I've done to fix it.
Rather than using javascript to move around pages, I've made a HTML form do it.
There is also no more GET variables in play anymore. The edit variable has been moved to POST.
Enough of my rambling, heres the code!
This part sits anywhere in the page.
<form method="POST" id="deleteacc">
<input type='hidden' name='delete_id' value='".$id."' />
</form>
This is the code for the button. It's location in the page is respective to where the button is displayed but otherwise didn't matter if it was in a form or not.
<button type="button" class="button" name="delete" value="Delete Account" onClick="deleteaccount_confirmation()" />Delete Account</button>
and lastly but not least the Javascript
function deleteaccount_confirmation() {
var answer = confirm("Are you sure you want to delete this account?")
if (answer){
$("#deleteacc").submit()
}
}
What the javascript does is simply triggers the submition of the form using jQuery. The javascript is assigned to any button which is why it doesn't need to be in the form. The form contains the data as a hidden variable which is triggered by the javascript.
Hope this helps everyone else!
I have a test page here: http://www.problemio.com/test.php
and if you press "Click To Test Signup" you get a form. If on that form, you click "Log In" it recognizes that you clicked that, and opens the login form.
But the problem is that on the login form, if you press "create profile" it actually goes to the url of the href tag and not to the jQuery click event.
My quetion is what is the best practice of doing this? I hered of something called "prevent default behavior" but not sure how/when it should be used.
I am guessing that if the user has JS disabled, they should still be able to log in. How can I set it up so that users can log in and make accounts in the jQuery way first, and some default way if they have JS disabled?
Thanks!
You can do this with pure jQuery with
$("#createprofilelink").click(function(event) {
event.preventDefault();
{create profile logic}
});
more details of this can be seen in the jQuery documentation http://api.jquery.com/event.preventDefault/
Edit: I removed this because of #maxedison comment that it stops the jQuery event from firing but I have just tested this and the jQuery event fires but the link does not go to the address.
<a id="thelink" href="http://www.google.com" onclick="return false;">the link</a>
<script>
$('#thelink').click(function(){alert('alert me');});
</script>
As for the JS being disabled part of the question the link really should point to to a real form to fill in, as Taryn East correctly says, so the user gets the same functionality even if the user experience is lower by not using JavaScript.
You could even go down the noscript route
<noscript>
<div>Your user experience would be far improved if you
enable JavaScript but if you insist,
Click Here to create your profile</div>
</noscript>
To fix you link-gazumping problem, indeed, as #kamui says, use return false;
But as to your JS-disabled question - point the href at a real URL -> preferably the same URL as your JS-enabled stuff - or the same form, but in a new window.
I could not follow the link due to firewall restrictions on my side but...
You'll want to use whats called unobtrusive javascript.
http://en.wikipedia.org/wiki/Unobtrusive_JavaScript
This means if JS is available it will use it, if not continue working as plain html.
using jQuery you would first attach the click event to your button in the $.Ready() method.
<a id='btnTest' href='login.html' />
$(document).ready(function () {
// Attach click event to btnTest
$("#btnTest").click(function (e) {
// do logic
return false; // Returning false here will stop the link from following login.html.
});
});
Hope this helps.
I want to add a confirm dialog to a delete button to ask the user whether it is ok or not deleting the selected item.
If not, nothing should happend, else a url should be executed.
I know how to realize this via some Javascript code but I am looking for a solution that has less code. I mean e.g. :
Delete
Is it possible to put the whole functionality in the onClick element without having some extra Javascript in the header?
You can return the confirm() (which returns true/false), like this:
Delete
You can test it here
Better (though far from ideal!): turn it around. Don't let the link do anything, unless you got JavaScript:
<a href="#"
onclick="if confirm('Sure?') { window.location='http://mysite.de/xy/delete';}">
Click to delete
</a>
This at least prevents the link to work without JavaScript. This also reduces the risk of the link accidentally being crawled by Google, or even by some local plugin. (Image if you had a plugin that would try to load/show as thumbnail) the target page on hover of a link!)
Still, this solution is not ideal. You will actually browse to the url, and the url might show up in the history because of that. You could actually delete Bob, create a new Bob, and then delete that one by accident by just clicking 'back' in the browser!
A better option would be to use JavaScript or a form to post the desired action. You can make a request to the server with the POST method, or arguably better, the DELETE method. That should also prevent the urls from being indexed.
Consider what happens if the user has javascript disabled, or if google comes along and spiders the link. Will your entity be deleted?
A better way would be to post a form to delete.
There is a jQuery plugin that does just that: jquery.confirm.
Example:
Go to home
JS code:
$('.confirm').confirm();
If the user confirms, he is redirected to the link of the <a>, else nothing happens.
You can use this:
Download a bootboxjs from:[1]: http://bootboxjs.com/
Create the Button (HTML)
<button type="submit" id="btn">Delete</button>
Call the Dialog:
var myBtn = document.getElementById('btn');
myBtn.addEventListener('click', function(event) {
bootbox.confirm({
size: "small",
message: "Are you sure?",
callback: function (result) {
/* result is a boolean; true = OK, false = Cancel*/
if (result == true) {
alert("ok pressed");
}
else {
alert("cancel pressed");
}
}
})
});