Warm tip: This article is reproduced from stackoverflow.com, please click
html iframe javascript jquery

How to get the origin of iframe object

发布于 2020-04-11 22:24:38

I need to get the origin of an iframe. Until now the code we used created an anchor element and read it's origin, but this attribute is not available in Internet Explorer. What is the most elegant way to get the origin from an iframe object?

Here is the old code:

function getOrigin(href) {
  var l = document.createElement("a");
  l.href = href;
  return l.origin;
};

var x = document.getElementById("my-iframe");
alert(getOrigin(x.src));

But as i said the origin attribute is not supported in Internet Explorer.

I need to support Internet Explorer 10 and up.

Questioner
Nick Russler
Viewed
37
smnbbrv 2015-09-04 18:19

Well it is quite dirty to create element to just parse a string.

Why don't just parse it yourself?

'http://stackoverflow.com:8080/123?param=test'.match(/^.+\:\/\/[^\/]+\//)[0]

If you also want to support relative urls (e.g. '/myurl') just add some condition to take current window's URL instead:

location.href.match...