How to change part of an iFrame’s URL to a random

2019-07-17 15:34发布

Consider this simple iFrame:

<iframe src="http://example.com/iframe/?user=123&name=test"
  width="200" height="200"></iframe>

What I want is to randomly change the part test.

For example change this

src="http://example.com/iframe/?user=123&name=test"

to something like this:

src="http://example.com/iframe/?user=123&name=yxcvb"

The string should contain random letters of the alphabet and have a length of up to 10 characters, e.g.:

src="http://example.com/iframe/?user=123&name=qwertzuiop"

1条回答
啃猪蹄的小仙女
2楼-- · 2019-07-17 15:59

I believe this could work for you: Random alpha-numeric string in JavaScript?

Just generate a random string (between 1 and 10 characters), and then assign it to the name attribute of the iframe.

I've put together a fiddle for you: http://jsfiddle.net/4agLwfe8/.

<iframe id="iframe" src="http://www.facebook.com?user=123&name=test" width="200" height="200">

This solution assumes you aren't using JQuery, since you said you weren't sure how to do this anyway, so it's a simply JavaScript solution.

To start you have a simple iframe. I just used facebook as a quick example. I also added an ID to it.

Then I used the following JavaScript

function randomNumber(){
    return Math.floor(Math.random() * 10) + 1;  
}

function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
    return result;
}

var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
var iframe = document.getElementById("iframe");
var iframeSrc = iframe.src;
var newIframeSrc = iframe.src.substring(0,iframe.src.indexOf("name")) + "name=" + randomString(randomNumber(), chars);
iframe.src = newIframeSrc;

First there are 2 functions. The first generates a random number between 1 and 10, this will be the length of the characters for your "name" parameter in your query string. The second function generates this random string, passing in the random number than was generated, and the string of characters (from the initial solution I linkted to) you specified you could use.

From there, I am simply selecting the iframe by the ID I gave it and grabbed it's source. With the source, I am simply cutting out the "name" parameter and it's value with the substring, and then appending the new "name" parameter and it's new value back on. Finally I'm assigning the new source for the iframe back to the iframe. In hindsight I realized I could have avoided chopping off "name=" only to add it back on again, but I started looking at this at 6:30am before my brain was fully awake. :)

查看更多
登录 后发表回答