How to disable the 'Open Link in New Tab' in the browser?

前端 未结 4 1646
攒了一身酷
攒了一身酷 2021-02-05 16:16

How do I disable/remove the \'Open Link in New Tab\' option in the right-click menu of the browser? If this is not possible with javascript etc then is there a way to modify wh

4条回答
  •  梦如初夏
    2021-02-05 17:05

    The ability to open a link in a new tab/window is native functionality of many browsers. If you do not wish to allow this type of activity, then you need to notify the browser that your link is not truly a link. The easiest way to do so is to remove the href attribute from your a element.

    HTML:

    Can be opened in new tab/window
    Cannot be opened in new tab/window
    

    Now there are some other things that the browser may be doing for you by default when it sees a link. If you have not defined any styling of a elements, it's likely that your new fancy pseudo-link will not appear with a link font-color, pointer, and underline. You can go ahead and do that easily enough.

    CSS:

    a {
        color: blue;
        cursor: pointer;
        text-decoration: underline;
    }
    

    That hopefully answers the question of how you disable/remove the 'Open Link in New Tab' option in the right-click menu of the browser. For some extra credit though I'm going to assume that you probably want the link to still function like a regular link when clicked. Feel free to use some JavaScript to make that happen. Here's an example using jQuery:

    JavaScript:

    $("body").on("click", "a[data-href]", function() {
        var href = $(this).data("href");
        if (href) {
            location.href = href;
        }
    });
    

    Modified Html:

    Can be opened in new tab/window
    Cannot be opened in new tab/window
    

    Modified CSS:

    a[href], a[data-href] {
        color: blue;
        cursor: pointer;
        text-decoration: underline;
    }
    

    Hope this helps!

提交回复
热议问题