如何手动调度hashchange事件

How to manually dispatch hashchange event

本文关键字:事件 hashchange 调度 何手动      更新时间:2023-09-26

1-WebKit(主要用于iPad上的Safari,如果它在Win-Chrome上工作,则很好)到.addEventListenerhashChange事件的正确语法是什么?

2-是否可以(以及如何)在上述浏览器上通过.dispatchEvent手动/编程地调度hashChange事件?

TIA。

我找到了1:的答案

window.addEventListener("hashchange", function() {console.log(location.hash)});

但我仍然不知道如何发送hashchange手册,因为我不知道应该将什么EVENTOBJECT传递给window.dispatchEvent(EVENTOBJECT)

如果您想在不直接更改哈希的情况下强制执行hashchcange事件,您应该调用:

window.dispatchEvent(new HashChangeEvent("hashchange"))

传递给事件处理程序的对象将有以下道具可用:

String oldURL;
String newURL;

这是我发现的关于这个的唯一信息:

https://github.com/WebKit/webkit/blob/master/Source/WebCore/dom/HashChangeEvent.h

在这里收到答案后:

http://forum.php.pl/index.php?showtopic=213470

以下是如何使其在Internet Explorer(IE11)上也能工作的

/**
 * cross browser hash change event dispatch
 */
function dispatchHashchange() {
    if (typeof HashChangeEvent !== "undefined") {
        window.dispatchEvent(new HashChangeEvent("hashchange"));
        return;
    }
    // HashChangeEvent is not available on all browsers. Use the plain Event.
    try {
        window.dispatchEvent(new Event("hashchange"));
        return;
    } catch (error) {
        // but that fails on ie
    }
    // IE workaround
    const ieEvent = document.createEvent("Event");
    ieEvent.initEvent("hashchange", true, true);
    window.dispatchEvent(ieEvent);
}