Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

javascript - Set URL before iframe load

Im trying to incorporate a sidebar to our company website. The problem is that this is an afterthought and i want to change as little code as possible(ive already created the whole layout and backend logic). I figured i can just create the a new html document and use a iframe that points back to the "original site".

I also want the sidebar part of the document to not be reloaded. So in every endpoint there is a check if the url containts the argument "sidebar", if this isnt the case JS vil change the src of the iframe to the same url with the added "sidebar" argument. This works as expected, the only problem is that when this happens the iframe does a single flickering since it will first load the whole page before executing the javascript(this is currently set as a 'load' eventlistener on the iframe). Ive tried to look for a eventlistener that fires before the actual load but cant seem to find anything. Is there a solution where i dont have to rewrite to much code?

JS:

iframe.addEventListener('load', ()=>{
        let newUrl = String(iframe.contentWindow.location.href)
        if(!newUrl.includes("sidebar=True")){
            if(newUrl.includes("?")){
                newUrl += "&sidebar=True"
            }else {
                newUrl += "?sidebar=True"
            }
            iframe.src = newUrl
        }
    })

Flask:

def test_render(site, **args):
    print(request.args.get("sidebar"))
    if(request.args.get("sidebar")):
        return render_template(site, **args)
    else:
        return render_template("test.html", page=request.path)

The "test render" function is just to test the idea. Test.html is the html file with the sidebar logic in.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. href is a string - neater to use the URL api

    let url = new URL(iframe.contentWindow.location.href);
    let sb = url.searchParams.get("sidebar");
    if (!sb) { 
      url.searchParams.set("sidebar","True")
      iframe.location.replace(url.toString())
    }
    
  2. is it not quicker to not reload, but simply add some css?

    if (top!==parent) document.write(`<style>#sidebar { display: none }</style>`)
    
  3. You can add transitions


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...