0

I am developing an extension in which i need to generate URL of website differently.Here is the structure of my code i am using

<script>
var URL="";
function genURL(){
URL="xyz";
}
</script>
<body onload="genURL()">
<iframe id="if1" src="abc"></iframe>
</body>
<script>
document.getElementById("if1").src=URL;
</script>

above code is wrong as i cannot access element if1 in script code aboveits definitions and URL is not available in below script code.If we can access URL in Script code below , my problem will be solved. Or else is there a way to generate URL directly in iframe .

Thanks

5
  • declare the URL variable as a global variable. var URL = "xyz" Commented Feb 6, 2011 at 13:06
  • You never seem to actually execute genURL, so URL won't be set... Commented Feb 6, 2011 at 13:06
  • @Aivan: the variable will be global because the var keyword is omitted. It won't work in IE, but I guess that doesn't really matter for a chrome extension. Still, the bigger problem is that genURL isn't called at all, Commented Feb 6, 2011 at 13:09
  • @David, you are right, he must have called it before executing his document.getElementById() function or as soon as the dom is loaded Commented Feb 6, 2011 at 13:30
  • The error i get on executing the code in chrome is : <Uncaught ReferenceError: URL is not defined (anonymous function)> Commented Feb 6, 2011 at 18:36

2 Answers 2

5

URL is not set at the time you're setting the iframes src. If you were to invoke genURL first, then your code would work. It would be far better, however, to design your code as such:

function getURL() {
    return "xyz";
};

...

document.getElementById('if1').src = getURL();
Sign up to request clarification or add additional context in comments.

Comments

1

You create a function that assigns a value to URL, but you never call the function, so the code is created but not executed. There're a couple of ways to fix this. One is David's way. Another is to assign a value to URL outside of the function:

<script>
URL="xyz";
</script>

<iframe id="if1" src="abc"></iframe>
<script>
document.getElementById("if1").src=URL;
</script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.