javascript window.print() access is denied - javascript

I'm loading an image from a different domain in a img html element via $.ajax cross domain call and opening up a popup with the contents of the image as you can see in the code below
var printWindow= "";
methodName = "CreateVisitor";
$.support.cors = true;
$.ajax({
type: "get",
url: visitorServiceUrl + methodName + "/" + tenantId + "/" + userId
+ "/" + visitorid + "/" + visitorname + "/" + visitormobilenumber
+ "/" + visitorcompanyid + "/" + visitorcompanyname + "/" + visiteeid,
dataType: "jsonp",
async: false,
cache: false,
crossDomain: true,
success: function (data) {
var imageUrl = "";
imageUrl = data ? siteImageUrl + data : 'image/NO_IMAGE.jpg';
$("#visitorcard").attr('src', imageUrl);
printWindow = window.open($("#visitorcard").attr('src'), "_blank", 'width=200,height=200');
// printWindow.onload = function () {
// printWindow.print();
// };
setTimeout(function () { printvisitorcard(); }, 1000);
},
error: function (xhr, type, exception) {
//alert("Error: " + xhr + " : " + exception + " : " + type);
}
});
I then use a setTimeout() to try to automatically print the image to my network printer (I'm not sure if I'm in the same domain or not) like this
function printvisitorcard() {
printWindow.print();
printWindow.close();
}
However each time I'm getting a Microsoft JScript runtime error: Access is denied. on the printWindow.print(); line. I'm aware of cross domain issue with javascript but I still want to print the image. How do I overcome this error? Any help will be appreciated.
P.S
Firefox and Chrome do not throw this error however they also do not print the image.

change to something from your own domain.
Here is a DEMO - works in Fx - to work in Chrome, you need to add a click handler. Popups are blocked unless the user clicked to get it
success: function (data) {
var imageUrl = data ? siteImageUrl + data : 'image/NO_IMAGE.jpg';
$("#visitorcard").attr('src', imageUrl);
var printWindow = window.open("", "_blank", 'width=200,height=200');
printWindow.document.write('<body onload="window.focus();window.print()">'+
$("#visitorcard").parent().html()+'</body>');
printWindow.document.close();
},

Related

Handling file download from ajax get request in JavaScript

I am using a python CGI server to handle a cgi-bin request that I am making from an ajax call.
I'm trying to download the information I'm receiving on the Python side from my browser, using a button that triggers the ajax call.
I have tried some different things I saw on StackOverflow, but nothing has helped.
function issueDownloadCmd(port) {
var statusURL = window.location.protocol + "//" + window.location.host + "/cgi-bin/sod_log.py" + "?" + "down" + port.toString();
$.ajaxSetup({ 'cache': true });
$.ajax({
type: 'GET',
url: statusURL,
error: function (xhr, desc, exception) {
$('#traceStatus').html("Fail: response=" + xhr.status + "\nbecause: " + desc + "\nexception: " + exception);
},
success: function (data) {
console.log("data was downloaded");
}
});
return false;
}

Windows Translator: "ArgumentOutOfRangeException: 'to' must be a valid language

Im trying to use Bing Translator...
Already Have a token (I think), but when try to get the translation, the same Error is always poping:
"ArgumentOutOfRangeException: 'to' must be a valid language\u000d\u000aParameter name: to : ID=5217.V2_Json.Translate.5FEAF805"
The next is the url that i am using, and I dont see where the error is...
https://api.microsofttranslator.com/V2/Ajax.svc/Translate?
&appId=Bearer%20http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=TranslateHelper000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1439307776&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=xGQ7LMehBDHJLY2Xq7jN8PXOhRCYqs%2boUb2V4Ic4XLI%3d
&from=en
&to=pt
&text=Home
&oncomplete=mycallback
(pt is defined as language in translator... it doesn't work either with to=en...
My question are, if you could help me on this:
1. Is that a normal Token?
2. Is it is normal, what is wrong with code? (I dont have any more hair to take off...)
This is the code I use to send the url (mycallback isn't being called either):
$.ajax({
type: "POST",
url: 'getTranslatorToken',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (token) {
var languageFrom = "en";
var languageTo = "pt";
var textToTranslate = "Home";
var strToken = token["access_token"];
var s = document.createElement("script");
//s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=Bearer " + token + "&from=" + languageFrom + "&to=" + languageTo + "&text=" + $('#txtMsg').val();
s.src = "https://api.microsofttranslator.com/V2/Ajax.svc/Translate?&appId=Bearer " + strToken +
"&from=" + encodeURIComponent(languageFrom) +
"&to=" + encodeURIComponent(languageTo) +
"&text=" + encodeURIComponent(textToTranslate) +
"&oncomplete=mycallback";
document.getElementsByTagName("head")[0].appendChild(s);
console.log(s)
}).fail(function (xhr, ajaxOptions, thrownError) {
alert("Error:"+xhr.responseText);
console.log(xhr.responseText);
//$("#msg").text('Error');
});
Thank
This question is answered here (in C#):
How to translate specific content in website
Working example here (PHP): http://www.johndimm.com/FunWithSpeech/BingTranslator/

getting an error Object doesn't support property or method 'setSrc' in web Resource in CRM 2011

I have used the WebResource on the Page and I am getting an error Object doesn't support property or method 'setSrc' in Javascript
Can you Please help me
My actual code is like this
function getImage()
{
var entityId = Xrm.Page.data.entity.getId();
var profilePictureElement = Xrm.Page.getControl("WebResource_ProfilePicture");
if (entityId) {
var oDataQuery = getServerUrl() + "/XRMServices/2011/OrganizationData.svc" +
"/AnnotationSet?$top=1&$select=AnnotationId,DocumentBody,MimeType&" +
"$orderby=ModifiedOn desc&$filter=ObjectId/Id eq guid'" + entityId +
"' and IsDocument eq true and Subject eq 'Profile Picture'" +
" and startswith(MimeType,'image/') ";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: oDataQuery,
beforeSend: function (request) { request.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, request) {
if (data.d.results.length > 0) {
var mimeType = data.d.results[0].MimeType;
var body = data.d.results[0].DocumentBody;
// set src attribute of default profile picture web resource.
// here we use DataURI schema which has 32kb limit in IE8 and doesn't support IE <= 7.
profilePictureElement.setSrc("data:" + mimeType + ";base64," + body);
}
},
error: function (request, status, exception) { }
});
}
}
function getServerUrl()
{
var serverUrl = Xrm.Page.context.getServerUrl();
// trim trailing forward slash in url
return serverUrl.replace(/\/*$/, "");
}
you can refer the whole article from here http://blogs.msdn.com/b/crm/archive/2011/09/28/displaying-a-contact-s-facebook-picture-in-microsoft-dynamics-crm-2011.aspx?CommentPosted=true#commentmessage
Looks like that now the methods getSrc and setSrc can be used against a Web Resource only when refer to an HTML content.
If the Web Resource is an image, the crm will use an img tag to display the picture.
If you want to make that code working you need to retrieve the img element and assign the src property manually:
instead of
profilePictureElement.setSrc("data:" + mimeType + ";base64," + body);
you need to write
var profilePicture = document.getElementById("WebResource_ProfilePicture");
profilePicture.setAttribute("src","data:" + mimeType + ";base64," + body);
note: this is an unsupported customization

How to reload page using Ajax

I have function addFeaturesToScene which make a new URL using ajax.
After the function ends I need to go to the new site automatically
Here is code:
function addFeatureToScene(featureNid, sceneNid)
{
alert(featureNid + " -> " + sceneNid);
$.ajax({
type : 'GET',
url : '/copy-feature-and-add-it-to-scene/' + featureNid + '/' + sceneNid,
dataType : 'json',
async : false,
success : function(reply) {
//Code to open a page with a new url?
}
});
}
You can use window.location
window.location.href = 'http://example.org';

Ajax call never gets called in phonegap for android

I searched similar questions but never found a proper answer. I am making app for multiple platforms using phonegap and JQM. I made index.html, which is "login page", with similar call. Index's call works, but the one below never gets called on my android device, even though it works both on chrome and safari.
I checked sever logs and there are no problems with "login", but as I said, there is no request from my android device when function below should be called.
//document.addEventListener("deviceready", onDeviceReady, true);
$( document ).bind( "mobileinit", function(){
$.support.cors = true;
$.mobile.allowCrossDomainPages = true;
$.mobile.loadingMessageTextVisible = true;
$.mobile.showPageLoadingMsg();
console.log('Page Started');
})
//var onDeviceReady = function(){
$( document ).ready(function (){
console.log('Start');
//$.support.cors = true;
//$.mobile.allowCrossDomainPages = true;
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://ip/services/rest/contact/list',
callback: 'jsonpCallback',
jsonpCallback: 'jsonpCallback',
jsonp: '_jsonp',
contentType: 'application/json',
dataType: 'jsonp json',
timeout : 10000,
success: function(data){
var html ='';
console.log('Success');
$.each(data.response, function(key, value) {
html += '<li><a class=contact href="#" id="' + data.response[key].id + '" ><h1>' + data.response[key].label + '</h1><p>'+ data.response[key].customerName + '</p><p>' + data.response[key].phone + ', ' + data.response[key].email + '</p></a></li>';
$('#ul_id').append($(html));
html='';
console.log('conatct');
});
$('#ul_id').trigger('create');
$('#ul_id').listview('refresh');
},
error: function (xhr, ajaxOptions, thrownError){
alert("Status: " + xhr.status + ", Ajax option: " + ajaxOptions + ", Thrown error: " + thrownError);
//location.reload();
console.log('Blad');
},
});
});
What is the access origin value in your Android project config.xml file ?
your value should be as below :
<access origin=".*"/>
There was a problem with placing script and specific way that jqm work.

Categories

Resources