I got issue CORS policy error when call ajax function in android webview. I sent android the following script using text type from server.
api_ticket.php
$ad_script = "<script>
function ad_click(link, str, id){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == '1'){ window.location.href = link;
}else{
alert('Server error');
}
}
};
xmlhttp.open('GET','https://skinexam.com/clients/ad_click_count.php?update='+str+'&id='+id,true);
xmlhttp.setRequestHeader('Access-Control-Allow-origin', '*');
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'POST,GET, PUT, OPTIONS, DELETE');
xmlhttp.setRequestHeader('Access-Control-Max-Age', '3600');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with, content-type');
xmlhttp.send();
}
</script>";
And then, I load webview in android.
.java file in android
txtDocReply.loadDataWithBaseURL(null, ticketModel.getTreatment(), "text/html", "utf-8", null);
ticketModel.getTreatment() have the following text.
webview
"<a onclick="ad_click(link, str, id)">some text</a>
<script>
function ad_click(link, str, id){
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if(this.responseText == '1'){ window.location.href = link;
}else{
alert('Server error');
}
}
};
xmlhttp.open('GET','https://skinexam.com/clients/ad_click_count.php?update='+str+'&id='+id,true);
xmlhttp.setRequestHeader('Access-Control-Allow-origin', '*');
xmlhttp.setRequestHeader('Access-Control-Allow-Methods', 'POST,GET, PUT, OPTIONS, DELETE');
xmlhttp.setRequestHeader('Access-Control-Max-Age', '3600');
xmlhttp.setRequestHeader('Access-Control-Allow-Headers', 'x-requested-with, content-type');
xmlhttp.send();
}
</script>";
When click on some text in webview, I call onclick function in android webview. onclick function is working well. But there are error in ajax call.
error
I/chromium: [INFO:CONSOLE(0)] "Access to XMLHttpRequest at 'https://skinexam.com/clients/ad_click_count.php?update=1&id=46' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.", source: about:blank (0)
I am going to call ad_click_count.php of server from android webview. so webview should be redirect. There are any good idea? Please help me. Thanks