Home > OS >  HTML and Native Javascript Change Iframe content based on search query
HTML and Native Javascript Change Iframe content based on search query

Time:10-30

I've made a website that utilizes Bootstrap's tab navigation. For my blog, I have an iframe set into one of these tabs. I am currently trying to make it so that if I were to give someone a link with the query ?blogPost=a_post it would automatically redirect the SRC of the Iframe to /blog/a_post.html. I started by setting up the script to get the queries based on this article: https://www.sitepoint.com/get-url-parameters-with-javascript/. Then, I adapted the code to look like this:

function onl oad() {
            let queryString = window.location.search;
            let urlParams = new URLSearchParams(queryString);
            if (urlParams.has('blogPost')) {
              let blogPost = urlParams.get('blogPost');
              document.getElementById('pills-home-tab').classList.remove('active');
              document.getElementById('pills-blog-tab').classList.add('active');
              document.getElementById("child-iframe").src = `./blog/${blogPost}.html`;
            } else {
              return;
            }
          }
          window.onload = onl oad;

However, when I load the page https://website.com/?blogPost=welcome_to_my_blog none of the classList properties change, and the Iframe stays at /blog.html

I'm not sure where I'm going wrong, but I'm certain what I'm trying to do is possible, and under that assumption know I am at error in my code. No errors come up on my browser's console, either.

CodePudding user response:

You declared a global function called onload, this has overwritten the native window.onload, making it not work. You can change the name of your function, or just add directly like this:

window.onload = () => {
        let queryString = window.location.search;
        let urlParams = new URLSearchParams(queryString);
        if (urlParams.has("blogPost")) {
          let blogPost = urlParams.get("blogPost");
          document.getElementById("pills-home-tab").classList.remove("active");
          document.getElementById("pills-blog-tab").classList.add("active");
          document.getElementById("child-iframe").src = `./blog/${blogPost}.html`;
        }
      };
  • Related