How to simulate target=“_blank” in JavaScript

前端 未结 7 1721
旧巷少年郎
旧巷少年郎 2020-12-02 08:05

When a user clicks on a link, I need to update a field in a database and then open the requested link in a new window. The update is no problem, but I don\'t know how to op

7条回答
  •  情话喂你
    2020-12-02 08:19

    I know this is a done and sorted out deal, but here's what I'm using to solve the problem in my app.

    if (!e.target.hasAttribute("target")) {
        e.preventDefault();     
        e.target.setAttribute("target", "_blank");
        e.target.click();
        return;
    }
    

    Basically what is going on here is I run a check for if the link has target=_blank attribute. If it doesn't, it stops the link from triggering, sets it up to open in a new window then programmatically clicks on it.

    You can go one step further and skip the stopping of the original click (and make your code a whole lot more compact) by trying this:

    if (!e.target.hasAttribute("target")) {
        e.target.setAttribute("target", "_blank");
    }
    

    If you were using jQuery to abstract away the implementation of adding an attribute cross-browser, you should use this instead of e.target.setAttribute("target", "_blank"):

        jQuery(event.target).attr("target", "_blank")
    

    You may need to rework it to fit your exact use-case, but here's how I scratched my own itch.

    Here's a demo of it in action for you to mess with.

    (The link in jsfiddle comes back to this discussion .. no need a new tab :))

提交回复
热议问题