neminem
neminem

Reputation: 2698

How to set an iframe's src to the same page (with a different anchor)

I have a demo page. In that page is a textbox and an iframe. When the value in the textbox changes, the iframe should be updated to a new url based on that value (in reality, the textbox is hidden, and is changing based on a more complicated lookup, but that's irrelevant to this question). The code for that should be pretty straight-forward:

$(document).ready(function(){
  $(".id-textbox").change(function(){
    var entryId=$(".id-textbox").val();
    var srcTxt='http://[site]/#id=' + entryId;
    var iframe = $('.webaccess-iframe iframe');
    iframe.attr('src',srcTxt);
  });
});

The issue is the url, and the fact that it looks like: http://[site]/#id={some id} If you visit that page, specifying an id, it will actually open up the page to the document with the id you specified - I have no control over that, that's how you use that site, which I didn't write.

If you type a valid id into the textbox the first time, the src of the iframe is set, the page loads correctly, and everything is great. If you then type a different valid id in, though, the src of the iframe is set to the new url, and then nothing happens, because the browser (at least in Firefox) still thinks it's pointing to the same url. After all, it technically is the same url - it's not the browser's fault the site we're trying to visit uses anchors that way.

I tried giving it the url and then refreshing the iframe (with contentDocument.location.reload()), but that didn't seem to change the behavior. I also tried giving it about:blank and then the url. That worked exactly half the time: as you type valid ids, it loads your page, then it loads about:blank instead of the next page, then it loads a page correctly, then it loads about:blank instead, etc.

Is there any way to force the iframe to actually load the new url?

Upvotes: 1

Views: 2976

Answers (3)

Luca De Feo
Luca De Feo

Reputation: 807

This behavior seems to be specific to Firefox. A bug, maybe ?

Note that if the page in the iframe is on the same domain as the container page, you can do (pure JavaScript)

iframe.contentDocument.location.replace(srcTxt);

This won't work if the iframe is pointing to a page on a different domain, as contentDocument won't be readable by JavaScript.

Upvotes: 1

Jacob Mattison
Jacob Mattison

Reputation: 51052

As a somewhat hacky workaround, an iFrame will regard a change to a querystring as a new URL -- but most servers will ignore querystrings they aren't expecting. So as a fix, you can add a meaningless querystring that will change every time (say a datestamp).

For example:

var srcTxt='http://[site]/?myCrazyQuerystring=' + new Date().getTime() + '#id=' + entryId;

Upvotes: 4

Meehow
Meehow

Reputation: 1061

http://[site]/#{some id}

without id=

Upvotes: 0

Related Questions