Javascript/jQuery: programmatically follow a link

做~自己de王妃 提交于 2019-12-30 05:48:12

问题


In Javascript code, I would like to programmatically cause the browser to follow a link that's on my page. Simple case:

<a id="foo" href="mailto:somebody@example.com">something</a>

function goToBar() {
   $('#foo').trigger('follow');
}

This is hypothetical as it doesn't actually work. And no, triggering click doesn't do it.

I am aware of window.location and window.open but these differ from native link-following in some ways that matter to me: a) in the presence of a <base /> element, and b) in the case of mailto URLs. The latter in particular is significant. In Firefox at least, calling window.location.href = "mailto:somebody@example.com" causes the window's unload handlers to fire, whereas simply clicking a mailto link does not, as far as I can tell.

I'm looking for a way to trigger the browser's default handling of links, from Javascript code.

Does such a mechanism exist? Toolkit-specific answers also welcome (especially for Gecko).


回答1:


As far as I know, window.location does exactly what you are looking for, triggering the browser's default link clicking behavior.

Some browsers notice the protocol before any events are fired or the actual href is changed.

window.location = "mailto:somebody@example.com";

Trying the fiddle demo mentioned below I get the following results:

  • Chromium: fires onbeforeunload with the button and link
  • Firefox fires onbeforeunload only for the button
  • Safari: never fires onbeforeunload
  • Opera: same as Safari

So a good way to prevent the unload event from being fired is by returning false in beforeunload.




回答2:


METHOD 1 click method

HTMLElements have a method click() https://developer.mozilla.org/en/DOM/element.click

function goToBar() {
   document.getElementById('foo').click();
}

Method 2 Firing synthetic events

I wonder why saluce deleted his answer. That solution is what I've used in the past (when click was an IE only thing). That is, firing a synthetic browser event (not a fake one like jQuery's click()). Let me post a solution using that idea...

DEMO: http://jsfiddle.net/eyS6x/3/

/**
 * Fire an event handler to the specified node. Event handlers can detect that the event was fired programatically
 * by testing for a 'synthetic=true' property on the event object
 * @param {HTMLNode} node The node to fire the event handler on.
 * @param {String} eventName The name of the event without the "on" (e.g., "focus")
 */
function fireEvent(node, eventName) {
  // Make sure we use the ownerDocument from the provided node to avoid cross-window problems
  var doc;
  if (node.ownerDocument) {
    doc = node.ownerDocument;
  } else if (node.nodeType == 9 /** DOCUMENT_NODE */){
    // the node may be the document itself
    doc = node;
  } else {
    throw new Error("Invalid node passed to fireEvent: " + +node.tagName + "#" + node.id);
  }

  if (node.fireEvent) {
    // IE-style
    var event = doc.createEventObject();
    event.synthetic = true; // allow detection of synthetic events
    node.fireEvent("on" + eventName, event);
  } else if (node.dispatchEvent) {
    // Gecko-style approach is much more difficult.
    var eventClass = "";

    // Different events have different event classes.
    // If this switch statement can't map an eventName to an eventClass,
    // the event firing is going to fail.
    switch (eventName) {
      case "click":
      case "mousedown":
      case "mouseup":
        eventClass = "MouseEvents";
        break;

      case "focus":
      case "change":
      case "blur":
      case "select":
        eventClass = "HTMLEvents";
        break;

      default:
        throw "JSUtil.fireEvent: Couldn't find an event class for event '" + eventName + "'.";
        break;
    }
    var event = doc.createEvent(eventClass);
    var bubbles = eventName == "change" ? false : true;  
    event.initEvent(eventName, bubbles, true); // All events created as bubbling and cancelable.

    event.synthetic = true; // allow detection of synthetic events
    node.dispatchEvent(event);
  }
};

document.getElementById('button').onclick = function() {
   fireEvent( document.getElementById('link'), 'click');
}


来源:https://stackoverflow.com/questions/10906197/javascript-jquery-programmatically-follow-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!