test
is undefined because open()
is declared void
, it does not return any value. Check out MDN on the open
method.
Why are you passing null
to send
? (see edit) If you intend to call the overload of send that doesn't take any argument you should just call req.send()
; instead if you want to call another version of the method you should pass a Blob, Document, DOMString or FormData, but null won't work.
EDIT: Often the method is invoked as send(null)
; it seems to be because at some point in history (is that old?) the argument of send
was mandatory. This question unravels the mystery.
Moreover, again send
doesn't return any value so the condition in the if
will never evaluate true. MDN documents also the send
method.
Last, you are performing a cross-domain request, i.e. you're asking for content that is located on another domain. XMLHttpRequest
doesn't handle that, most likely you will end up with this error:
XMLHttpRequest cannot load link. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin origin is therefore not allowed access.
Check out this question and this on StackOverflow if you need more information about that.
You may want to take a look at Using XMLHttpRequest again on the MDN network, it has many reliable examples that can help you get acquainted with these requests.
EDIT: expanding on the topic iframe embeddability.
Detecting reliably if a website can be embedded in an iframe
is difficult, as this question shows. Detecting (or preventing) frame buster in JavaScript is like a dog chasing its own tail.
Nevertheless, a website that doesn't want to be incorporated, hopefully would send the X-Frame-Options: DENY
header in its response. This is not very useful, because you can't perform cross domain requests: your request would fail before getting to know if the X-Frame-Options
header is even set. For completeness, this is the way of checking if the response to an XMLHttpRequest
contains a given header (but note that this would work only within the same domain, which is presumably under your control, and you would know already if a page is 'frameable'):
function checkXFrame() {
var xframe = this.getResponseHeader("X-Frame-Options");
if (!xframe) {
alert("Frameable.");
return;
}
xframe = xframe.toLowerCase();
if (xframe == "deny") {
alert("Not frameable.");
} else if (xframe == "sameorigin") {
alert("Frameable within the same domain.");
} else if (xframe.startsWith("allow-from")) {
alert("Frameable from certain domains.");
} else {
alert("Someone sent a weird header.");
}
}
var oReq = new XMLHttpRequest();
oReq.open("HEAD" /* use HEAD if you only need the headers! */, "yourpage.html");
oReq.onload = checkXFrame;
oReq.send();
(this code doesn't check for 404 or any other error!)