2012-06-05 3 views
12

자바 스크립트 코드에서 프로그래밍 방식으로 브라우저가 내 페이지의 링크를 따라 가도록하고 싶습니다. 간단한 경우 :Javascript/jQuery : 프로그래밍 방식으로 링크 따라 가기

<a id="foo" href="mailto:[email protected]">something</a> 

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

이 실제로 작동하지 않는 가설이다. 그리고 아니오, click을 유발하지 않습니다.

나는 window.locationwindow.open의 알고 있지만, 이들은 나에게 문제가 어떤 방법으로 다음과 같은 링크를 모국어 다를 : A)는 A <base /> 요소의 존재와 b) mailto URL의 경우이다. 후자는 특히 중요합니다. Firefox에서 적어도 window.location.href = "mailto:[email protected]"을 호출하면 unload 핸들러가 실행되지만, 단순히 mailto 링크를 클릭하는 것은 내가 알 수있는 한 멀리하지 않습니다.

자바 스크립트 코드에서 브라우저의 기본 링크 처리를 트리거하는 방법을 찾고 있습니다.

이러한 메커니즘이 있습니까? 툴킷 관련 답변도 환영합니다 (특히 Gecko의 경우).

+0

왜 mailto : 링크에 target = "_ blank"속성을 사용하지 않는 것이 좋습니까? –

+0

할 수는 있지만 빈 창이 열리는 반면 메일 클라이언트는 열리지 만 브라우저는 그대로 유지됩니다. – Dan

+0

jsFiddle 예제가 Firefox Aurora 14.0a2 (2012-06-04)와 함께 작동합니다. –

답변

17

지금까지 내가,에서는 window.location는 브라우저의 기본 링크 클릭을 유발, 찾고있는 정확하게 수행 알고 행동.

일부 브라우저는 이벤트가 시작되거나 실제 href가 변경되기 전에 프로토콜을 확인합니다.

  • 크롬 : 화재 버튼 및 링크 onbeforeunload
  • 파이어 폭스는 버튼
  • 사파리 onbeforeunload를 발생 : 나는 다음과 같은 결과를 얻을 수 아래에 언급 된 바이올린 데모를 시도

    window.location = "mailto:[email protected]"; 
    

    결코 화재 onbeforeunload

  • 오페라 : 사파리와 동일

unload 이벤트가 발생하지 않도록하는 좋은 방법은 beforeunload에 false를 반환하는 것입니다.

+0

아니,별로 동일하지 않습니다. http://jsfiddle.net/eyS6x/2/를 참조하십시오. "Click me"는'beforeunload' 핸들러를 호출하는데, 링크 자체는 그렇지 않습니다. – Dan

+0

충분하다. 여러 브라우저에서 이것을 시험해 보았는데, 동작이 상당히 다르게 보인다. 나는 그것을 반영하기 위해 나의 대답을 업데이트 할 것이다. –

+0

글쎄, 당신은 여기 뭔가있을 수 있습니다. 내 실제 코드에서는 _unly_'beforeunload'이고'unload'는 아닙니다. 나는 그 일을 엉망으로 망 쳤다. _inside_ 내 'beforeunload' 핸들러가 내가 mailto인지 여부를 감지 할 수있는 방법이 있습니까? – Dan

3

방법 1 클릭 방법

HTMLElement s는 방법 click()https://developer.mozilla.org/en/DOM/element.click

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

방법 2 발사 합성 이벤트

내가 saluce는 그의 대답을 삭제 한 이유를 궁금해에게 있습니다. 그 해결책은 내가 과거에 사용했던 것입니다 (클릭이 IE 전용 일 때). 즉, 합성 브라우저 이벤트를 발생시킵니다 (jQuery의 click()과 같은 가짜 이벤트는 아닙니다). ... 제가 그 아이디어를 사용하여 솔루션을 게시하자

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'); 
} 
+0

흠 .... 나는 그것을 시도하고 그것이 작동하지 않는다고 생각. 내가 다시 시도하자. – Dan

+0

실제로 그렇지 않습니다. http://jsfiddle.net/eyS6x/1/을 시도하고 "Click Me"를 클릭하십시오. 이것은 MacOS 용 Firefox 5.0에 있습니다. – Dan

+1

Windows에서 Chrome (19.0.1084.52 m), Firefox (10.0.3) 및 IE (8.0.7600)에서 작동합니다. Mac 문제 일 수 있습니다. –

관련 문제