OberDulli94
OberDulli94

Reputation: 187

Set customs HTTP Request Headers for Iframes

I want to set 2 HTTP request headers (X-Forwarded-For and User Agent) and display the website which I send my custom headers with Iframes in HTML. So I started writing a JavaScript and it works ok. It sends the right headers to my own website but won't connect to websites which aren't hosted by myself and I get the following error massage:

"Access to XMLHttpRequest at 'https://google.com/' from origin 'http://myserver.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource." .

Is there a way to fix this?

Here is my JavaScript code:

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {
    
    var xmlHttp;
    
    if(window.XMLHttpRequest){
        xmlHttp = new XMLHttpRequest();
    }
    else {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlHttp;
}

function process() {
    if(xmlHttp){
        try {
            xmlHttp.open("GET", "https://google.com", true);
            xmlHttp.setRequestHeader("X-Forwarded-For", "1.2.3.4")
            xmlHttp.onreadystatechange = handleServerResponse;
            xmlHttp.send(null);
        }
        catch(e){
            alert(  e.toString()    );
        }
    }
}

function handleServerResponse() {
    theD = document.getElementById('theD');
    
    if(xmlHttp.readyState==1) {
        theD.innerHTML += "Status 1: server connection established <br/>";      
    }
    
    else if(xmlHttp.readyState==2){
    theD.innerHTML += "Status 2: request recived <br/>";        
    }
    
    else if(xmlHttp.readyState==3){
    theD.innerHTML += "Status 3: processing request <br/>";     
    }
    
    else if(xmlHttp.readyState==4){
    
        if(xmlHttp.status==200) {
                try {
                            texxt = xmlHttp.responseText;
                            theD.innerHTML += "Status 4: request is finsihed, response is ready <br/>";     
                            theD.innerHTML += texxt;        
            }
                catch(e){
                    alert(  e.toString()    );
            }   
    }   
        }
        else {
            alert(  xmlHttp.statusText );       
        }   
    }   

Upvotes: 1

Views: 331

Answers (1)

shashank joshi
shashank joshi

Reputation: 148

By default, browsers block access from a webpage to a different website's webpage. It can be allowed using browser settings. No other way exists for this. However, some data can be posted using GET or POST to another website, for example in case of payment gateway.

Upvotes: 1

Related Questions