Eric
Eric

Reputation: 185

Why sometimes it fails to use window.location.href

I just encounter weird and inconsistent behavior. I type below in w3c online tester.

test.htm

<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<body>
<iframe onload="$.getScript('https://mysite.tw/test.js')">
</body>
</html>

where in test.js (on my server), I write:

alert('get!'); // this is just to confirm the js had indeed loaded
window.location.href="https://amazon.com";

Then the alert message jumps, but suddenly the browser blocks the redirect behavior, reporting the server refuses the access.

My first question is that why does this happen? I just want to direct to another site, not to make something complicate or sensitive, like Ajax, etc.

My second question is that I tried the similar code of test.htm on another site. And this time the page successfully redirect to amazon. Pretty weird. Is it due to the https problem? Or a cross-site security issue?

Upvotes: 1

Views: 746

Answers (1)

ProDec
ProDec

Reputation: 5410

You test.js is in iframe, and you may check the response header from https://www.amazon.com/

x-frame-options: SAMEORIGIN

You cannot iframe the web page from other domain.

The X-Frame-Options HTTP response header can be used to indicate whether or not a browser should be allowed to render a page in a <frame>, <iframe>, <embed> or <object>. Sites can use this to avoid click-jacking attacks, by ensuring that their content is not embedded into other sites.

SAMEORIGIN The page can only be displayed in a frame on the same origin as the page itself.

Upvotes: 2

Related Questions