最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the origin of iframe object - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited Sep 4, 2015 at 10:58 Nick Russler asked Sep 4, 2015 at 9:57 Nick RusslerNick Russler 4,7147 gold badges54 silver badges90 bronze badges 1
  • I tried to do something like this: x.contentWindow.location.origin but because of SOP i can't access it and i cannot add CORS. – Nick Russler Commented Sep 4, 2015 at 10:05
Add a ment  | 

2 Answers 2

Reset to default 5

var x = document.getElementById("myiframe");
alert(new URL(x.src).origin);
<iframe id="myiframe" src="https://www.google./search?q=test"></iframe>

to check if src is relative url: How to test if a URL string is absolute or relative?

to generate the absolute url of a relative url: Convert relative path to absolute using JavaScript

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

Why don't just parse it yourself?

'http://stackoverflow.: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...
发布评论

评论列表(0)

  1. 暂无评论