开发者

Send a cross-domain request to log data

开发者 https://www.devze.com 2023-03-15 01:31 出处:网络
I\'m working on an ad platform. When someone clicks on an image, I want to send a request开发者_运维知识库 back to my server to log this action. I have a pre-generated url for this. If I send a reques

I'm working on an ad platform. When someone clicks on an image, I want to send a request开发者_运维知识库 back to my server to log this action. I have a pre-generated url for this. If I send a request to this url, it will log the data.

My issue is that the log url is on my domain, whereas the javascript is being executed in a client's domain. Without modifying the logging php script (to add something like Access-Control-Allow-Origin: *), is there a way to send this request to the new domain?

Since I'm only logging data, the server only sends back the text "OK" (which is information I don't need).


You should be able to send Ajax HTTP requests to any domain. I don't see what the problem is... It's the response that is restricted with the Same Origin Policy, not the request itself. You cannot access the response of the PHP script if the domains don't match, but the server will process the request normally, even if it's from a different domain.


This is a hack but it's commonly used. On click append an image to the DOM with the src set to the logging URL. To be friendly, have the output from the logging URL be a 1x1 pixel image. You'll have to pass the parameters via a GET string but it will work.


Create any dynamic DOM element with source on your domain (image or iframe), append a logging data to a request.

var logData = function(data){
if(data === undefined){
    return;
}

var img=document.createElement("img");
img.setAttribute('src', 'http://another.domain?'+data);
img.setAttribute('height', '1px');
img.setAttribute('width', '1px');
document.body.appendChild(img);}

Your log requests will now appear in IIS logs


Cross-domain script restrictions are enforced at the browser level as a security precaution, so there is not a simple code fix to work around them. However, you can look at JSONP (JSON with padding) as a starting point.


You could create a hidden iframe with the src attribute set to the logging URL. This is at least as ugly as the image approach listed above.

0

精彩评论

暂无评论...
验证码 换一张
取 消