7
  1. 我已经注册了两个协议。
  2. 当我尝试在同一事件中调用这两种协议时,Chrome 浏览器中一次只能调用一个。

$(function () {
    $("div[href]").click(function (event) {
        debugger;
        //for validation purpose.
        window.location = "abcd:";

       //if it is validated then
        window.location ="xyz:";



    });
});
<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title>Custom Protocol Detection</title>
</head>

<body id="abcd">
    <h1>Click one of these labels:</h1>
    <a href="#" id="atemp"></a>
    <div href="blahblah:randomstuff"  style="background-color:aquamarine">
        Non-exist protocol
    </div>
    <div href="mailto:johndoe@somewhere.com" style="background-color:aqua">
        Send email
    </div>
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>   
    <script src="example.js"></script>
</body>

</html>

  1. 请让我知道如何在同一事件中调用这两个协议。
4

1 回答 1

0

此函数将自定义协议 URL 作为参数。然后它会创建一个临时<iframe>的,通过模拟点击隐藏<a>元素来加载传递的 URL。

    function invokeProtoLink(url) {
      return new Promise(function(resolve, reject) {
        // create temp frame where url will be opened
        const frame = document.createElement('iframe');
        frame.name = '_invoker_' + Math.random();

        // create temp link and set it's target to temp frame
        const lnk = document.createElement('a');
        lnk.href = url;
        lnk.target = frame.name;

        // frame must be appended to body otherwise link will
        // open in new tab, and might trigger popup blocker
        document.body.appendChild(frame);

        setTimeout(function() {
          // remove temp frame
          frame.parentNode.removeChild(frame);
          resolve();
        }, 0);

        // a simple lnk.click() did not work in firefox
        // hence we're using dispatchEvent
        lnk.dispatchEvent(new MouseEvent('click'))
      });
    }

基于您的示例的用法是:(这必须在事件处理程序中,例如onclick

    invokeProtoLink('abcd://').then(() => {
      invokeProtoLink('xyz://');
    });

在 Chrome 68、Edge 42 和 Firefox 61 上测试。

于 2018-08-26T11:25:21.853 回答