Preventing pages being open in a new tab/window

前端 未结 3 488
悲&欢浪女
悲&欢浪女 2020-12-31 15:19

I am working on a project that behaves very strange when the user open pages in a new tab or in a new window, causing the app to crash.

I need some javascript that

相关标签:
3条回答
  • 2020-12-31 15:19

    Replace all < a > tags attribute to _self, that will force the broswer to open the hyperlink in a new tab

    Array.prototype.forEach.call(document.getElementsByTagName('a'), function(el, i){
    if(el.target=="_blank"){ el.target="_self" }
    });
    
    0 讨论(0)
  • 2020-12-31 15:20

    Instead of

    <a href="http://stackoverflow.com">link</a>
    

    use

    <a href="javascript:void(0);" onclick="javascript:window.location.href='http://stackoverflow.com';">link</a>
    

    Middle mouse click opens this location in the same tab, right click -> open in new tab opens about:blank page.


    When you can't edit every link manually you can use this script:

    for(var els = document.getElementsByTagName('a'), i = els.length; i--;){
        els[i].href = 'javascript:void(0);';
        els[i].onclick = (function(el){
            return function(){
                window.location.href = el.getAttribute('data-href');
            };
        })(els[i]);
    }
    

    and instead of <a href="..."> use <a data-href="...">.


    Going further, you may change script above to following:

    for(var els = document.getElementsByTagName('a'), i = els.length; i--;){
        var href = els[i].href;
        els[i].href = 'javascript:void(0);';
        els[i].onclick = (function(el, href){
            return function(){
                window.location.href = href;
            };
        })(els[i], href);
    }
    

    this way links stay the same <a href="...">, but if user has disabled JavaScript, links may be opened in another tab/window.

    0 讨论(0)
  • 2020-12-31 15:24

    For me, the other answers are no sensible option, since some hrefs in my document are procedurally changed. This block of code works though:

    document.documentElement.addEventListener('click', function (event) {
      if(event.ctrlKey){event.preventDefault()}
    });
    
    0 讨论(0)
提交回复
热议问题