I have reCAPTCHA v3 set up on my page:
<script src="https://www.google.com/recaptcha/api.js?render=MY_KEY"></script>
If internet connectivity becomes unavailable or unreliable, reCAPTCHA will insert this HTML at the bottom of my page:
<div>
<div>
Could not connect to the reCAPTCHA service. Please check your internet connection and reload to get a reCAPTCHA challenge.
</div>
</div>
I would much rather handle this error in my JavaScript so I can display it to the user in a better way. However, the documentation for v3 doesn't indicate how to do this.
Any thoughts on how to catch this error?
You can put an onerror handler in the script tag itself:
<script src="https://www.google.com/recaptcha/api.js?render=MY_KEY" onerror="error_handler()">
But I think what you want is more along the lines of what reCAPTCHA v2 offers:
widgetId = grecaptcha.render('example1', {
'sitekey' : 'your_site_key',
'theme' : 'light',
'error-callback' : error_handler()
});
I doubt that works but there is another way. You just need to monitor the DOM for changes since you know that when there is an error Google will add a div to your page. You can do that with MutationObserver.
var m = new MutationObserver(function (mutationRecords) {
this.disconnect();
error_handler();
});
m.observe(document.body, {childList: true});
{childList: true} tells the MutationObserver to detect nodes added to the DOM and passes them to the callback function as the parameter mutationRecords (which contains array of MutationRecord objects). From there it's up to you what to do next.
This should at least be enough to get you started!
Related
I'm keen to use reCAPTCHA v3 for logins and stuff, but I'm unsure what to do with a 'low rating', it doesn't feel safe to deny access with no way for the user to move forward. What feels like a more complete solution would be to combine the "rating" from v3 with a puzzle challenge from v2 if the score is too low. How are other people approaching this issue?
Also, it appears that v3's grecaptcha.execute returns a similar result to v2, that is too say that it's not returning a rating, just a TOKEN which is verified in a similar way to v2?
I've code i found to demonstrate that they can both be used in the same HTML...
<!-- https://github.com/google/recaptcha/issues/279 -->
<script src="https://www.google.com/recaptcha/api.js?onload=v2_onload"></script>
<script src="https://www.google.com/recaptcha/api.js?onload=v3_onload&render=V3_SITE_KEY"></script>
<script src='https://www.google.com/recaptcha/api.js?render=V3_SITE_KEY'></script>
<div class="g-recaptcha" data-size="invisible" data-sitekey="V2_SITE_KEY" data-callback="v2_callback"></div>
<script type="text/javascript">
function v2_onload() { console.log('v2 loaded'); }
function v3_onload() { console.log('v3 loaded'); }
function v2_callback(token) { console.log('v2 token: ' + token); }
function v3_callback(token, score) { console.log('v3 token: ' + token + " ----- " + score); }
// call these manually
function test_v2() { grecaptcha.execute(); }
function test_v3() {
grecaptcha.execute('V3_SITE_KEY' , {action:'thisIsATest' }).then(v3_callback);
}
I have concerns then that if v3 requires sever-side validation, in order to implement v2 as well, either a page reload to invoke v2 (when server-side says "low rating" then reload and enable v2) OR v3 sever-side validation could be done via an ajax call, but that feels like something that can be inspected and manipulated by a bot (grab ajax response, change 'no' to 'yes' and then have the bot call the 'callback' function itself to gain access).
Any help or suggestions would be appreciated.
It looks like there is an answer to this question on the official Frequently Asked Questions website of reCAPTCHA.
Can I run reCAPTCHA v2 and v3 on the same page?
To do this, load the v3 site key as documented, and then explicitly render v2 using grecaptcha.render.
<html>
<head>
<title>reCAPTCHA demo: Running both v2 and v3</title>
<script src="https://www.google.com/recaptcha/api.js?render=v3_site_key"></script>
<script>
grecaptcha.ready(() => {
grecaptcha.render('html_element', {
'sitekey' : 'v2_site_key'
});
});
</script>
<script>
function onSubmit() {
grecaptcha.ready(() => {
grecaptcha.execute('v3_site_key', {action: 'homepage'}).then((token) => {
...
});
});
}
</script>
</head>
</html>
Wouldn't it be simplest to just send the token with your form post and double check it server side? I know you're still possibly allowing a bot to post data into your system, but a bot that can sneak by google should be pretty rare. And the first thing your sever side logic should do is verify the token, which can't easily be faked. That said in my initial analysis of google V3(10K requests) the bot detection was solidly binary, in that all the scores were above or below .5 . Google in their documentation recommends different strategies for how to deal with suspicious traffic based on the scenario.
https://developers.google.com/recaptcha/docs/v3.
I'm working in an implementation of ReCaptcha from Google in my Joomla 1.5 application. I know, it's an old version of Joomla, but as the time got passed, the hard code practice at the company made the upgrading impossible.
I found an old ReCaptcha plugin for Joomla 1.5 at https://code.google.com/p/joomla-recaptcha/, by the way, recommended by developers.google (https://developers.google.com/recaptcha/old/intro).
That plugin is really simple to use. Enough to install the plugin and enable it. This way it's only a matter of use its static methods. One thing I had to do was change the path to the ReCaptcha ajax API, both in components/com_community/helpers/recaptcha.php and in plugins/system/recaptcha/recaptchalib.php. That's because the plugin reference the old path.
I'm working well with server side part of ReCaptcha. So I'm mostly concerned with a client-side issue. To display ReCaptcha snippet, is only a matter of include the line
<div><?php echo ReCaptcha::get('html'); ?></div>
in the template .php.
The ReCaptcha::get static method generates the following piece of code in my template
<div>
<div id='recaptcha_ajax_instance_'></div>
<script type='text/javascript' src='http://www.google.com/recaptcha/api/js/recaptcha_ajax.js'></script>
<script type='text/javascript'>
(function(){
function loadRecaptcha(){
Recaptcha.create('6LcKaAgTAAAAAP3CgGF04VUsWTPGwzDs3EaVlajH','recaptcha_ajax_instance_');
}
if( window.addEvent ){
window.addEvent('domready', loadRecaptcha);
}
else{
if( window.addEventListener ){ window.addEventListener('load', loadRecaptcha); }
else if( window.attachEvent ){ window.attachEvent('onload', loadRecaptcha); }
else{ old = window.onload; window.onload = function(){ if( old && typeof old == 'function'){ old(); } loadRecaptcha(); }; }
}
})();
</script>
</div>
That issue is simply the button to reload captcha doesn't work. Neither mouse changes to pointer when hovering button, nor button change the words when clicked. The two other buttons (audio chalange and help) work well.
I wondering if the code above is outdated with the most updated API in google URL.
If somebody could help, I appreciate.
I am learning ASP.NET MVC. I have to submit a to controller side after validation in client-side(in jquery). How this can be done? Should i use <form action="#" method="post"> instead of <form action="Controller/Method" method="post"> and add an event handler in click event of submit button of , to send via ajax etc? What should i do? pls help
You are on the right track, and what you suggested will work.
A better method would be to leave the original action intact, providing backwards compatibility to older browsers. You would then create the event handler as normal, and include code to prevent the default submit behavior, and use ajax instead.
$('#submitbutton').live('click', function(e){ e.preventDefault(); });
The easiest way to do this is to use the jQuery forms plugin.
This is my go-to plugin for this type of thing. Basically it will take your existing form, action url etc and convert the submission to an ajax call automatically. From the website:
The jQuery Form Plugin allows you to easily and unobtrusively upgrade
HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit,
gather information from the form element to determine how to manage
the submit process. Both of these methods support numerous options
which allows you to have full control over how the data is submitted.
It is extremely useful for sites hosted in low cost web hosting
providers with limited features and functionality. Submitting a form
with AJAX doesn't get any easier than this!
It will also degrade gracefully if, for some reason, javascript is disabled. Take a look at the website, there are a bunch of clear examples and demos.
This is how I do:
In jQuery:
$('document').ready(function() {
$('input[name=submit]').click(function(e) {
url = 'the link';
var dataToBeSent = $("form#myForm").serialize();
$.ajax({
url : url,
data : dataToBeSent,
success : function(response) {
alert('Success');
},
error : function(request, textStatus, errorThrown) {
alert('Something bad happened');
}
});
e.preventDefault();
});
In the other page I get the variables and process them. My form is
<form name = "myForm" method = "post">//AJAX does the calling part so action is not needed.
<input type = "text" name = "fname"/>
<input type= "submit" name = "submit"/>
<FORM>
In the action page have something like this
name = Request.QueryString("fname")
UPDATE: As one of your comment in David's post, you are not sure how to send values of the form. Try the below function you will get a clear idea how this code works. serialize() method does the trick.
$('input[name=submit]').click(function(e){
var dataToBeSent = $("form#myForm").serialize();
alert(dataToBeSent);
e.preventDefault();
})
I'm trying to set up a basic web page, and it has a small music player on it (niftyPlayer). The people I'm doing this for want the player in the footer, and to continue playing through a song when the user navigates to a different part of the site.
Is there anyway I can do this without using frames? There are some tutorials around on changing part of a page using ajax and innerHTML, but I'm having trouble wrapping my head aroung getting everything BUT the music player to reload.
Thank you in advance,
--Adam
Wrap the content in a div, and wrap the player in a separate div. Load the content into the content div.
You'd have something like this:
<div id='content'>
</div>
<div id='player'>
</div>
If you're using a framework, this is easy: $('#content').html(newContent).
EDIT:
This syntax works with jQuery and ender.js. I prefer ender, but to each his own. I think MooTools is similar, but it's been a while since I used it.
Code for the ajax:
$.ajax({
'method': 'get',
'url': '/newContentUrl',
'success': function (data) {
// do something with the data here
}
});
You might need to declare what type of data you're expecting. I usually send json and then create the DOM elements in the browser.
EDIT:
You didn't mention your webserver/server-side scripting language, so I can't give any code examples for the server-side stuff. It's pretty simple most of time. You just need to decide on a format (again, I highly recommend JSON, as it's native to JS).
I suppose what you could do is have to div's.. one for your footer with the player in it and one with everything else; lets call it the 'container', both of course within your body. Then upon navigating in the site, just have the click reload the page's content within the container with a ajax call:
$('a').click(function(){
var page = $(this).attr('page');
// Using the href attribute will make the page reload, so just make a custom one named 'page'
$('#container').load(page);
});
HTML
<a page="page.php">Test</a>
The problem you then face though, is that you wouldnt really be reloading a page, so the URL also doesnt get update; but you can also fix this with some javascript, and use hashtags to load specific content in the container.
Use jQuery like this:
<script>
$("#generate").click(function(){
$("#content").load("script.php");
});
</script>
<div id="content">Content</div>
<input type="submit" id="generate" value="Generate!">
<div id="player">...player code...</div>
What you're looking for is called the 'single page interface' pattern. It's pretty common among sites like Facebook, where things like chat are required to be persistent across various pages. To be honest, it's kind of hard to program something like this yourself - so I would recommend standing on top of an existing framework that does some of the leg work for you. I've had success using backbone.js with this pattern:
http://andyet.net/blog/2010/oct/29/building-a-single-page-app-with-backbonejs-undersc/
You can reload desired DIVs via jQuery.ajax() and JSON:
For example:
index.php
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<a href='one.php' class='ajax'>Page 1</a>
<a href='two.php' class='ajax'>Page 2</a>
<div id='player'>Player Code</div>
<div id='workspace'>workspace</div>
one.php
<?php
$arr = array ( "workspace" => "This is Page 1" );
echo json_encode($arr);
?>
two.php
<?php
$arr = array( 'workspace' => "This is Page 2" );
echo json_encode($arr);
?>
ajax.js
jQuery(document).ready(function(){
jQuery('.ajax').click(function(event) {
event.preventDefault();
// load the href attribute of the link that was clicked
jQuery.getJSON(this.href, function(snippets) {
for(var id in snippets) {
// updated to deal with any type of HTML
jQuery('#' + id).html(snippets[id]);
}
});
});
});
EDIT: The problem is not related to Boxy, I've run into the same issue when I've used JQuery 's load method.
EDIT 2: When I take out link.remove() from inside the ajax callback and place it before ajax load, the problem is no more. Are there restrictions for manipulating elements inside an ajax callback function.
I am using JQuery with Boxy plugin.
When the 'Flag' link on the page is clicked, a Boxy modal pops-up and loads a form via ajax. When the user submits the form, the link (<a> tag) is removed and a new one is created from the ajax response. This mechanism works for, well, 3 times! After the 3rd, the callback function just does not remove/replace/append (tested several variations of manipulation) the element.
The only hint I have is that after the 3rd call, the parent of the link becomes non-selectable. However I can't make anything of this.
Sorry if this is a very trivial issue, I have no experience in client-side programming.
The relevant html is below:
<div class="flag-link">
<img class="flag-img" style="width: 16px; visibility: hidden;" src="/static/images/flag.png" alt=""/>
<a class="unflagged" href="/i/flag/showform/9/1/?next=/users/1/ozgurisil">Flag</a>
</div>
Here is the relevant js code:
$(document).ready(function() {
$('div.flag-link a.unflagged').live('click', function(e){
doFlag(e);
return false;
});
...
});
function doFlag(e) {
var link = $(e.target);
var url = link.attr('href');
Boxy.load(url, {title:'Inappropriate Content', unloadOnHide:true, cache:false, behaviours: function(r) {
$("#flag-form").live("submit", function(){
var post_url = $("#flag-form").attr('action');
boxy = Boxy.get(this);
boxy.hideAndUnload();
$.post(post_url, $("#flag-form").serialize(), function(data){
par = link.parent();
par.append(data);
alert (par.attr('class')); //BECOMES UNDEFINED AT THE 3RD CALL!!
par.children('img.flag-img').css('visibility', 'visible');
link.remove();
});
return false;
});
}});
}
Old and late reply, but.. I found this while googling for my answer, so.. :)
I think this is a problem with the "notmodified" error being thrown, because you return the same Ajax data.
It seems that this is happening even if the "ifModified" option is set to false (which is also the default).
Returning the same Ajax data three times will cause issues for me (jQuery 1.4). Making the data unique (just adding time/random number in the response) removes the problem.
I don't know if this is a browser (Firefox), jQuery or server (Apache) issue though..
I have had the same problem, I could not run javascript after I call boxy. So I put all my javascript code in afterShow:function one of boxy attributes. I can run almost except submit my form. My be my way can give you something.