Home > Software design >  Calling iframe link from other js file not working
Calling iframe link from other js file not working

Time:11-16

I created an iframe in vex6.html and a js file in styles.gq/test.js and in that file there is the link and id but when I try to call the code in html it does not work.

Here is my code for vex6.html

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<script type="text/javascript" src="https://styles.gq/test.js" ></script>

<iframe id="vex6" width="100%" height="500" style="border:1px solid black;"></iframe>


</body>
</html>

here is my js code

document.getElementById("vex3").src
    = "https://www.obviousplays.tk/gfiles/vex3";

document.getElementById("vex4").src
    = "https://www.obviousplays.tk/gfiles/vex4";
    
document.getElementById("vex5").src
    = "https://www.obviousplays.tk/gfiles/vex5";
    
document.getElementById("vex6").src
    = "https://www.obviousplays.tk/Gfiles6/vex6";
    
document.getElementById("slope").src
    = "https://www.obviousplays.tk/gfiles/slope";

I expected an iframe but instead there seems to be no link for the iframe it is also spitting out the error cannot set properties of null (setting(src))

CodePudding user response:

Add the line <script type="text/javascript" src="https://styles.gq/test.js</script> after the iframe tag.

Worked for me.

CodePudding user response:

Error in console: "script.js:3 Uncaught TypeError: Cannot set properties of null (setting 'src')"

Your script is loaded before the iframe content, meaning that you're trying to initialize the source of an unidentified object.

Solution: Place the <script> tag below your iframe. It is a good practice to place <script> tags at the bottom of the <body> tag so we can always access loaded content. However, sometimes it takes the contents a little bit more time until they fully load (despite placing the <script> tag at the bottom of the page). I'd suggest wrapping your code in window.onload = () {} It will ensure that all contents are loaded before firing the code.

<body>

<iframe id="vex3" width="100%" height="500" style="border:1px solid black;"></iframe>

<script type="text/javascript" src="https://styles.gq/test.js"></script>

</body>

Your code is fine and should work (pardon for criticizing). Anytime you seem to use repetitive code, it means that it can be simplified/automated like so:

window.onload = () => {
  // Target all <iframe> tags.
  iframes = document.querySelectorAll('iframe');

  // Loop through list of <iframe> nodes.
  Array.from(iframes).map(iframe => {
    // Update <iframe>'s attribute "src" to the origin URL,
    // and use the iframe's attribute "id" value as the final source.
    iframe.setAttribute('src', `https://www.obviousplays.tk/gfiles/${iframe.id}`)
  });
}
  • Related