Prevent preflight OPTIONS when using sub domains - javascript

Given two sub domains:
web.mysite.com and api.mysite.com
Currently making any request from web. to api. results in the preflight OPTIONS request being made. This wouldn't be so much of an issue if it didn't add an extra 600ms to requests in China.
I was told that setting document.domain = 'mysite.com'; in JS would resolve the issue but this hasn't helped at all.
Is it possible / how can I disable the OPTIONS request when sending to just a different sub domain.

Solved this using the iframe technique which seems to be what Facebook / Twitter do.
Steps below:
1) Set the document.domain to be the root domain. So given the url http://site.mysite.com/ I set the domain in JavaScript like document.domain = 'mysite.com';
2) Setup an iframe which pulls a HTML file from the API Domain.
<iframe id="receiver" src="http://api.mysite.com/receiver" style="position:absolute;left:-9999px"></iframe>
This is set to be positioned so it can't be seen.
3) Set the HTML of the receiver page to set the domain:
<!DOCTYPE html><body><script>document.domain='mysite.com'</script></body></html>
4) Added an onload event to the iframe to capture the window once its loaded.
onload="window.tempIframeCallback()"
5) Assign the child window to a variable.
window.tempIframeCallback = function() {
window.childWindow = window.receiver.contentWindow;
}
6) Make the XMLHttpRequest() from the childWindow instead of the main window.
var xhr = new window.childWindow.XMLHttpRequest();
Now all requests will be sent without a preflight OPTIONS request.
7) When using jQuery, you can also set the source of xhr in the settings:
$.ajax({
...
xhr: function() {
return new window.childWindow.XMLHttpRequest();
}
});

As a complement to #Phill's answer that deserves all the credits, here is the final html code, that also exposes the iframe's fetch function:
<!DOCTYPE html>
<html><body>
<script>
document.domain = 'mysite.com';
window.setupAPI = function() {
var receiverWindow = window.receiver.contentWindow;
// you may also want to replace window.fetch here
window.APIfetch = receiverWindow.fetch;
// same thing, you may as well replace window.XMLHttpRequest
window.APIXMLHttpRequest = receiverWindow.XMLHttpRequest;
}
</script>
<iframe id="receiver"
src="http://api.mysite.com/receiver"
style="position:absolute;left:-9999px"
onload="window.setupAPI()"></iframe>
</body></html>
And of course the HTML "http://api.mysite.com/receiver" should retrieve:
<!DOCTYPE html>
<html><body><script>
document.domain='mysite.com';
</script></body></html>
And then, within your JS code, you can now use APIfetch and APIXMLHttpRequest like you'd use fetch and XMLHttpRequest ... et voilĂ , no more preflight request whatever the method and content type used!

Here's an all javascript approach:
document.domain = 'mysite.net';
var apiIframe = document.createElement('iframe');
apiIframe.onload = function(){
window.XMLHttpRequest = this.contentWindow.XMLHttpRequest;
};
apiIframe.setAttribute('src', API_URL + '/iframe');
apiIframe.style.display = 'none';
document.body.appendChild(apiIframe);
where API_URL + '/iframe' returns this:
<!DOCTYPE html><body><script>document.domain = 'mysite.net'</script></body></html>

Related

Fetch url of html page inside an iframe [duplicate]

Is there a simple way to get the current URL from an iframe?
The viewer would going through multiple sites.
I'm guessing I would be using something in javascript.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
document.getElementById("iframe_id").contentWindow.location.href
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
See also answers to a similar question.
If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:
var currentUrl = document.referrer;
and - here you've got the main url!
If you are in the iframe context,
you could do
const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);
If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is
document.getElementById("iframe_id").contentWindow.location.href
I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:
const iframeReference = document.getElementById("iframe_id");
const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
if (iframeUrl) {
console.log("Voila: " + iframeUrl);
} else {
console.warn("iframe with id iframe_id not found");
}
Hope this will help some how in your case,
I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe.
So in parent window you can:
localStorage.setItem("url", myUrl);
And in code where iframe source is just get this data from localstorage:
localStorage.getItem('url');
Saved me a lot of time.
As far as i can see the only condition is access to the parent page code.
Hope this will help someone.
If you're inside an iframe that don't have cross domain src, or src is empty:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Check if window.frameElement not null
if(window.frameElement) {
href = window.frameElement.ownerDocument.location.href;
// This one will be origin
if(window.frameElement.ownerDocument.referrer != "") {
referrer = window.frameElement.ownerDocument.referrer;
}
}
// Compare if href not equal to referrer
if(href != referrer) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href
}
}
If you're inside an iframe with cross domain src:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Detect if you're inside an iframe
if(window.parent != window) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href;
}
}
I've been trying to retrieve the full URL from the inside of the shopify google analytics additional script iframe. document.refferer shows only hostname without search params. But I found another property that worked for me document.baseURI
Some additional information for anyone who might be struggling with this:
You'll be getting null values if you're trying to get URL from iframe before it's loaded.
I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:
var iframe = document.createElement('iframe');
iframe.onload = function() {
//some custom settings
this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";
var href = iframe.contentWindow.location.href;
var origin = iframe.contentWindow.location.origin;
var url = iframe.contentWindow.location.url;
var path = iframe.contentWindow.location.pathname;
console.log("href: ", href)
console.log("origin: ", origin)
console.log("path: ", path)
console.log("url: ", url)
};
iframe.src = 'http://localhost/folder/index.html';
document.body.appendChild(iframe);
Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.
Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

Create an embedded JavaScript in a Cross Domain Host Page which is not affected by the Host Page CSS?

Most javascript widget which can be embedded into a website use the following structure. First you embed a code snipped like this:
<script type="text/javascript">
window.$zopim||(function(d,s){var z=$zopim=function(c){
z._.push(c)},
$=z.s=d.createElement(s),
e=d.getElementsByTagName(s)[0];
z.set=function(o){
z.set._.push(o)
};
z._=[];
z.set._=[];
$.async=!0;
$.setAttribute('charset','utf-8');
$.src='//v2.zopim.com/?2342323423434234234';
z.t=+new Date;
$.type='text/javascript';
e.parentNode.insertBefore($,e)})(document,'script');
</script>
Then, when load your page this script creates a html structure like this:
<div class="widget-class">
<iframe src="about:blank">
// the content of the widget
</iframe>
</div
I see this same structure in many chat services like:
https://en.zopim.com/
http://banckle.com/
https://www.livechatinc.com/
All have in common that their iframe does not have a src, i.e., an URL attached.
Update: Here is the script I use to load my widget code into a third party website:
<script type="text/javascript">
(function(d){
var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT');
window.WidgetId = "1234";
p.type = 'text/javascript';
p.setAttribute('charset','utf-8');
p.async = true;
p.src = "//www.example.com/assets/clientwidget/chatwidget.nocache.js";
f.parentNode.insertBefore(p, f);
}(document));
</script>
I want that the CSS of the site where the GWT widget is integrated should not influence the CSS of the GWT widget. I will prevent that the CSS of the host page influence the CSS of my GWT widget.
Note: I want to have access to tho host website from my GWT widget too.
The domain of the host page is www.example.com and the domain of the iframe is www.widget.com. I also want to set cookies of the host domain from the iframe.
What is the procedure of building a widget running on such a structure? How is the content of the iframe being set? Is there a pattern for that? How can I do that with GWT
I don't know GWT, but you can easily achieve this in plain JavaScript.
Let's assume you're creating an online-count widget. At first, create an iframe:
<script id="your-widget">
// Select the script tag used to load the widget.
var scriptElement = document.querySelector("your-widget");
// Create an iframe.
var iframe = document.createElement("iframe");
// Insert iframe before script's next sibling, i.e. after the script.
scriptElement.parentNode.insertBefore(iframe, scriptElement.nextSibling);
// rest of the code
</script>
Then fetch the online count using JSONP (see What is JSONP all about?), for example:
// The URL of your API, without JSONP callback parameter.
var url = "your-api-url";
// Callback function used for JSONP.
// Executed as soon as server response is received.
function callback(count) {
// rest of code
}
// Create a script.
var script = document.createElement("script");
// Set script's src attribute to API URL + JSONP callback parameter.
// It makes browser send HTTP request to the API.
script.src = url + "?callback=callback";
Then handle server response (inside the callback() function):
// Create a div element
var div = document.createElement("div");
// Insert online count to this element.
// I assume that server response is plain-text number, for example 5.
div.innerHTML = count;
// Append div to iframe's body.
iframe.contentWindow.document.body.appendChild(div);
That's all. Your whole code could look like this:
Snippet to insert into third party website:
<script type="text/javascript">
(function(d){
var f = d.getElementsByTagName('SCRIPT')[0], p = d.createElement('SCRIPT');
window.WidgetId = "1234";
p.type = 'text/javascript';
p.setAttribute('charset','utf-8');
p.async = true;
p.id = "your-widget";
p.src = "//www.example.com/assets/clientwidget/chatwidget.nocache.js";
f.parentNode.insertBefore(p, f);
}(document));
</script>
JavaScript file on your server:
// Select the script tag used to load the widget.
var scriptElement = document.querySelector("#your-widget");
// Create an iframe.
var iframe = document.createElement("iframe");
// Insert iframe before script's next sibling, i.e. after the script.
scriptElement.parentNode.insertBefore(iframe, scriptElement.nextSibling);
// The URL of your API, without JSONP callback parameter.
var url = "your-api-url";
// Callback function used for JSONP.
// Executed as soon as server response is received.
function callback(count) {
// Create a div element
var div = document.createElement("div");
// Insert online count to this element.
// I assume that server response is plain-text number, for example 5.
div.innerHTML = count;
// Append div to iframe's body.
iframe.contentWindow.document.body.appendChild(div);
}
// Create a script.
var script = document.createElement("script");
// Set script's src attribute to API URL + JSONP callback parameter.
// It makes browser send HTTP request to the API.
script.src = url + "?callback=callback";
EDIT:
if you want your widget to not be influenced by any css from the "outside" you have to load into an iframe.
code to add to your website to load any gwt project/widget:
<iframe id="1234" src="//www.example.com/assets/Chatwidget.html" style="border: 1px solid black;" tabindex="-1"></iframe>
notice: that im NOT loading the nocache.js but the yourwidget.html file.
like this all your clases insde the frame wont be affected by any class from the outside.
to access anything outside ofthis iframe you can use jsni methods. this will only work if the domain of your iframe and the thirdpartysite are the same. otherwise youve to use window.postMessage:
public native static void yourMethod() /*-{
$wnd.parent.someMethodFromOutsideTheIframe();
}-*/;
EDIT2:
by using the snippet from above you make sure that your widget is not influened by any css from the hostpage.
to get the hostpage url from inside the widget simply add this function:
private native static String getHostPageUrl() /*-{
return $wnd.parent.location.hostname;
}-*/;
EDIT3:
since you are on 2 different domains, you have to use window.postMessage.
here one little example to get you going:
besides the iframe you have to add a event listener to the window of your example.com, that listens for the messages from your iframe. you also check if the messages comes form the correct origin.
<script>
// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener"
: "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage"
: "message";
// Listen to message from child window
eventer(messageEvent, function(e) {
//check for the correct origin, if wanted
//if ( e.origin !== "http://www.widget.com" )
// return
console.log('parent received message!: ', e.data);
//here you can set your cookie
document.cookie = 'cookie=widget; expires=Fri, 1 Feb 2016 18:00:00 UTC; path=/'
}, false);
</script>
From inside your widget you call this method:
public native static void postMessageToParent(String message) /*-{
//message to sent, the host that is supposed to receive it
$wnd.parent.postMessage(message, "http://www.example.com");
}-*/;
i put a working example on pastebin:
javascript to insert into your page: http://pastebin.com/Y0iDTntw
gwt class with onmoduleload: http://pastebin.com/QjDRuPmg
Here's a full functional simple widget expample project I wrote in cloud9 (online IDE) with javascript, please feel free to request an access if you want to edit it, viewing is publicly available (for registered users - registration is free).
sources:
https://ide.c9.io/nmlc/widget-example,
result:
https://widget-example-nmlc.c9users.io/index.html
As for the question about how do they do it:
It seems that zopim builds their widgets gradually on the client side, defining and requiring basic modules (like these __$$__meshim_widget_components_mobileChatWindow_MainScreen), which are consist from submodules and then process everything with __$$__jx_ui_HTMLElement builder which creates HTML elements and appends them to provided parent nodes. All that compiles to the resulting HTML of the chatbox. Btw, judging by the names of some components, it seems, they build their widgets with some "meshim" library, but I have never heard of this library.
this.dom.src='about:blank'
this.appendToParent(!0)
var H=this.iwin=this.dom.contentWindow
var I=this.idoc=r.extend(H.document)
I.write(G)
I.close()
This, I guess, is the place where zopim service creates an iframe for their widgets. I'm not sure why they are using document.write instead of appendChild (document.write drops event bindings), but I have implemented both versions - they are pretty much the same except setIframeContents and addHtmlElement functions.
Hope someone will find this useful :).
1) There are many different ways to load content to iframe. Iframe have isolated content. iframe that you put in host page, does not have src, because of browser secure politic, you can't simply load content from other domains. But you can load js from other domain.For this porpuse you need usw JSONP
2) to share cookies with host page and widget iframe, you need use postMessage api like in this post

Get script content [duplicate]

If I have a script tag like this:
<script
id = "myscript"
src = "http://www.example.com/script.js"
type = "text/javascript">
</script>
I would like to get the content of the "script.js" file. I'm thinking about something like document.getElementById("myscript").text but it doesn't work in this case.
tl;dr script tags are not subject to CORS and same-origin-policy and therefore javascript/DOM cannot offer access to the text content of the resource loaded via a <script> tag, or it would break same-origin-policy.
long version:
Most of the other answers (and the accepted answer) indicate correctly that the "correct" way to get the text content of a javascript file inserted via a <script> loaded into the page, is using an XMLHttpRequest to perform another seperate additional request for the resource indicated in the scripts src property, something which the short javascript code below will demonstrate. I however found that the other answers did not address the point why to get the javascript files text content, which is that allowing to access content of the file included via the <script src=[url]></script> would break the CORS policies, e.g. modern browsers prevent the XHR of resources that do not provide the Access-Control-Allow-Origin header, hence browsers do not allow any other way than those subject to CORS, to get the content.
With the following code (as mentioned in the other questions "use XHR/AJAX") it is possible to do another request for all not inline script tags in the document.
function printScriptTextContent(script)
{
var xhr = new XMLHttpRequest();
xhr.open("GET",script.src)
xhr.onreadystatechange = function () {
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log("the script text content is",xhr.responseText);
}
};
xhr.send();
}
Array.prototype.slice.call(document.querySelectorAll("script[src]")).forEach(printScriptTextContent);
and so I will not repeat that, but instead would like to add via this answer upon the aspect why itthat
Do you want to get the contents of the file http://www.example.com/script.js? If so, you could turn to AJAX methods to fetch its content, assuming it resides on the same server as the page itself.
Update: HTML Imports are now deprecated (alternatives).
---
I know it's a little late but some browsers support the tag LINK rel="import" property.
http://www.html5rocks.com/en/tutorials/webcomponents/imports/
<link rel="import" href="/path/to/imports/stuff.html">
For the rest, ajax is still the preferred way.
I don't think the contents will be available via the DOM. You could get the value of the src attribute and use AJAX to request the file from the server.
yes, Ajax is the way to do it, as in accepted answer. If you get down to the details, there are many pitfalls. If you use jQuery.load(...), the wrong content type is assumed (html instead of application/javascript), which can mess things up by putting unwanted <br> into your (scriptNode).innerText, and things like that. Then, if you use jQuery.getScript(...), the downloaded script is immediately executed, which might not be what you want (might screw up the order in which you want to load the files, in case you have several of those.)
I found it best to use jQuery.ajax with dataType: "text"
I used this Ajax technique in a project with a frameset, where the frameset and/or several frames need the same JavaScript, in order to avoid having the server send that JavaScript multiple times.
Here is code, tested and working:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html>
<head>
<script id="scriptData">
var scriptData = [
{ name: "foo" , url: "path/to/foo" },
{ name: "bar" , url: "path/to/bar" }
];
</script>
<script id="scriptLoader">
var LOADER = {
loadedCount: 0,
toBeLoadedCount: 0,
load_jQuery: function (){
var jqNode = document.createElement("script");
jqNode.setAttribute("src", "/path/to/jquery");
jqNode.setAttribute("onload", "LOADER.loadScripts();");
jqNode.setAttribute("id", "jquery");
document.head.appendChild(jqNode);
},
loadScripts: function (){
var scriptDataLookup = this.scriptDataLookup = {};
var scriptNodes = this.scriptNodes = {};
var scriptNodesArr = this.scriptNodesArr = [];
for (var j=0; j<scriptData.length; j++){
var theEntry = scriptData[j];
scriptDataLookup[theEntry.name] = theEntry;
}
//console.log(JSON.stringify(scriptDataLookup, null, 4));
for (var i=0; i<scriptData.length; i++){
var entry = scriptData[i];
var name = entry.name;
var theURL = entry.url;
this.toBeLoadedCount++;
var node = document.createElement("script");
node.setAttribute("id", name);
scriptNodes[name] = node;
scriptNodesArr.push(node);
jQuery.ajax({
method : "GET",
url : theURL,
dataType : "text"
}).done(this.makeHandler(name, node)).fail(this.makeFailHandler(name, node));
}
},
makeFailHandler: function(name, node){
var THIS = this;
return function(xhr, errorName, errorMessage){
console.log(name, "FAIL");
console.log(xhr);
console.log(errorName);
console.log(errorMessage);
debugger;
}
},
makeHandler: function(name, node){
var THIS = this;
return function (fileContents, status, xhr){
THIS.loadedCount++;
//console.log("loaded", name, "content length", fileContents.length, "status", status);
//console.log("loaded:", THIS.loadedCount, "/", THIS.toBeLoadedCount);
THIS.scriptDataLookup[name].fileContents = fileContents;
if (THIS.loadedCount >= THIS.toBeLoadedCount){
THIS.allScriptsLoaded();
}
}
},
allScriptsLoaded: function(){
for (var i=0; i<this.scriptNodesArr.length; i++){
var scriptNode = this.scriptNodesArr[i];
var name = scriptNode.id;
var data = this.scriptDataLookup[name];
var fileContents = data.fileContents;
var textNode = document.createTextNode(fileContents);
scriptNode.appendChild(textNode);
document.head.appendChild(scriptNode); // execution is here
//console.log(scriptNode);
}
// call code to make the frames here
}
};
</script>
</head>
<frameset rows="200pixels,*" onload="LOADER.load_jQuery();">
<frame src="about:blank"></frame>
<frame src="about:blank"></frame>
</frameset>
</html>
related question
.text did get you contents of the tag, it's just that you have nothing between your open tag and your end tag. You can get the src attribute of the element using .src, and then if you want to get the javascript file you would follow the link and make an ajax request for it.
In a comment to my previous answer:
I want to store the content of the script so that I can cache it and use it directly some time later without having to fetch it from the external web server (not on the same server as the page)
In that case you're better off using a server side script to fetch and cache the script file. Depending on your server setup you could just wget the file (periodically via cron if you expect it to change) or do something similar with a small script inthe language of your choice.
if you want the contents of the src attribute, you would have to do an ajax request and look at the responsetext. If you where to have the js between and you could access it through innerHTML.
This might be of interest: http://ejohn.org/blog/degrading-script-tags/
I had a same issue, so i solve it this way:
The js file contains something like
window.someVarForReturn = `content for return`
On html
<script src="file.js"></script>
<script>console.log(someVarForReturn)</script>
In my case the content was html template. So i did something like this:
On js file
window.someVarForReturn = `<did>My template</div>`
On html
<script src="file.js"></script>
<script>
new DOMParser().parseFromString(someVarForReturn, 'text/html').body.children[0]
</script>
You cannot directly get what browser loaded as the content of your specific script tag (security hazard);
But
you can request the same resource (src) again ( which will succeed immediately due to cache ) and read it's text:
const scriptSrc = document.querySelector('script#yours').src;
// re-request the same location
const scriptContent = await fetch(scriptSrc).then((res) => res.text());
If you're looking to access the attributes of the <script> tag rather than the contents of script.js, then XPath may well be what you're after.
It will allow you to get each of the script attributes.
If it's the example.js file contents you're after, then you can fire off an AJAX request to fetch it.
It's funny but we can't, we have to fetch them again over the internet.
Likely the browser will read his cache, but a ping is still sent to verify the content-length.
[...document.scripts].forEach((script) => {
fetch(script.src)
.then((response) => response.text() )
.then((source) => console.log(source) )
})
Using 2008-style DOM-binding it would rather be:
document.getElementById('myscript').getAttribute("src");
document.getElementById('myscript').getAttribute("type");
You want to use the innerHTML property to get the contents of the script tag:
document.getElementById("myscript").innerHTML
But as #olle said in another answer you probably want to have a read of:
http://ejohn.org/blog/degrading-script-tags/
If a src attribute is provided, user agents are required to ignore the content of the element, if you need to access it from the external script, then you are probably doing something wrong.
Update: I see you've added a comment to the effect that you want to cache the script and use it later. To what end? Assuming your HTTP is cache friendly, then your caching needs are likely taken care of by the browser already.
I'd suggest the answer to this question is using the "innerHTML" property of the DOM element. Certainly, if the script has loaded, you do not need to make an Ajax call to get it.
So Sugendran should be correct (not sure why he was voted down without explanation).
var scriptContent = document.getElementById("myscript").innerHTML;
The innerHTML property of the script element should give you the scripts content as a string provided the script element is:
an inline script, or
that the script has loaded (if using the src attribute)
olle also gives the answer, but I think it got 'muddled' by his suggesting it needs to be loaded through ajax first, and i think he meant "inline" instead of between.
if you where to have the js between and you could access it through innerHTML.
Regarding the usefulness of this technique:
I've looked to use this technique for client side error logging (of javascript exceptions) after getting "undefined variables" which aren't contained within my own scripts (such as badly injected scripts from toolbars or extensions) - so I don't think it's such a way out idea.
Not sure why you would need to do this?
Another way round would be to hold the script in a hidden element somewhere and use Eval to run it. You could then query the objects innerHtml property.

Get Current location of Iframe [duplicate]

Is there a simple way to get the current URL from an iframe?
The viewer would going through multiple sites.
I'm guessing I would be using something in javascript.
For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:
document.getElementById("iframe_id").contentWindow.location.href
If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.
See also answers to a similar question.
If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:
var currentUrl = document.referrer;
and - here you've got the main url!
If you are in the iframe context,
you could do
const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);
If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is
document.getElementById("iframe_id").contentWindow.location.href
I had an issue with blob url hrefs. So, with a reference to the iframe, I just produced an url from the iframe's src attribute:
const iframeReference = document.getElementById("iframe_id");
const iframeUrl = iframeReference ? new URL(iframeReference.src) : undefined;
if (iframeUrl) {
console.log("Voila: " + iframeUrl);
} else {
console.warn("iframe with id iframe_id not found");
}
Hope this will help some how in your case,
I suffered with the exact same problem, and just used localstorage to share the data between parent window and iframe.
So in parent window you can:
localStorage.setItem("url", myUrl);
And in code where iframe source is just get this data from localstorage:
localStorage.getItem('url');
Saved me a lot of time.
As far as i can see the only condition is access to the parent page code.
Hope this will help someone.
If you're inside an iframe that don't have cross domain src, or src is empty:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Check if window.frameElement not null
if(window.frameElement) {
href = window.frameElement.ownerDocument.location.href;
// This one will be origin
if(window.frameElement.ownerDocument.referrer != "") {
referrer = window.frameElement.ownerDocument.referrer;
}
}
// Compare if href not equal to referrer
if(href != referrer) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href
}
}
If you're inside an iframe with cross domain src:
Then:
function getOriginUrl() {
var href = document.location.href;
var referrer = document.referrer;
// Detect if you're inside an iframe
if(window.parent != window) {
// Take referrer as origin
return referrer;
} else {
// Take href
return href;
}
}
I've been trying to retrieve the full URL from the inside of the shopify google analytics additional script iframe. document.refferer shows only hostname without search params. But I found another property that worked for me document.baseURI
Some additional information for anyone who might be struggling with this:
You'll be getting null values if you're trying to get URL from iframe before it's loaded.
I solved this problem by creating the whole iframe in javascript and getting the values I needed with the onLoad function:
var iframe = document.createElement('iframe');
iframe.onload = function() {
//some custom settings
this.width=screen.width;this.height=screen.height; this.passing=0; this.frameBorder="0";
var href = iframe.contentWindow.location.href;
var origin = iframe.contentWindow.location.origin;
var url = iframe.contentWindow.location.url;
var path = iframe.contentWindow.location.pathname;
console.log("href: ", href)
console.log("origin: ", origin)
console.log("path: ", path)
console.log("url: ", url)
};
iframe.src = 'http://localhost/folder/index.html';
document.body.appendChild(iframe);
Because of the same-origin policy, I had problems when accessing "cross origin" frames - I solved that by running a webserver locally instead of running all the files directly from my disk. In order for all of this to work, you need to be accessing the iframe with the same protocol, hostname and port as the origin. Not sure which of these was/were missing when running all files from my disk.
Also, more on location objects: https://www.w3schools.com/JSREF/obj_location.asp

Load another page in jquery tooltip

My html code is:
<div class="ui-widget photo">
<div class="ui-widget-header ui-corner-all">
<h2>St. Stephen's Cathedral</h2>
<h3>Vienna, Austria</h3>
</div>
<div id="result"></div>
</div>
My Javascript code is:
$(function () {
$(document).tooltip({
items: "[href]",
content: function () {
var element = $(this);
if (element) {
var text = element.text();
var link = element.attr('href');
// alert(link);
return "<img class='map' alt='" + text +
"' src='http://maps.google.com/maps/api/staticmap?" +
"zoom=11&size=350x350&maptype=terrain&sensor=false&center=" +
"Vienna, Austria" + "'>";
}
}
});
});
This thing is given here :
jQuery tooltip
But Now I want to load another page from another url say : www.google.com in this tooltip.
what I am doing is:
I am putting .load() function in this content section so that I can get response html and return it into the tooltip
Here is my code but its not working I am getting nothing in response ...
$(function () {
$(document).tooltip({
items: "[href]",
content: function () {
$('#result').load('http://stackoverflow.com/', function (response, status, xhr){
var responseText = response;
});
var element = $(this);
if (element) {
var text = element.text();
var link = element.attr('href');
// alert(link);
return responseText;
}
}
});
});
$.load('http://stackoverflow.com');
Won't return anything because you're trying to load another web site. That's against how AJAX works.
From jQuery docs:
The .load() method, unlike $.get(), allows us to specify a portion of
the remote document to be inserted.
It allows the user to load a file on the same domain, not external ones, for security reasons.
If you observe this fiddle with firebug opened you can see that the call will return header 200 OK but will not load anything due to these restrictions.
To achieve what you want you could make a local file that fetches the desired page, then make an ajax call to it, instead of a directly calling the web site.
A simple example of using local php file to get the page.
Create a local file, I'll call it foo.php
<?php
echo file_get_contents($_GET['url']);
// this will echo contents of given url
?>
Mind, this is only an example code and is not for serious use
Then call it like this
$("#container").load("foo.php?url=google.com");
This is because you are trying to make a CORS (Cross Origin Resource Sharing) request.
And because of security concerns such requests are not entertained by browsers and servers unless the server returns Access-Control-Allow-Origin header with the requesting domain acceptable to it.
To know when does CORS come into play read this: http://en.wikipedia.org/wiki/Same_origin_policy#Origin_determination_rules
To know more about CORS read the following article http://www.html5rocks.com/en/tutorials/cors/.
To test if the server supports CORS you can use the following website: http://client.cors-api.appspot.com/client
An alternative would be to make a PHP proxy on your server and then make a CORS request through that proxy.
Here is a tutorial for creating your own PHP proxy http://jquery-howto.blogspot.in/2009/04/cross-domain-ajax-querying-with-jquery.html

Categories

Resources