Tampermonkey: Trigger event does not work for element

泪湿孤枕 提交于 2020-01-02 20:59:52

问题


I'm trying to add some functionality using Tampermonkey on top of a providers angular application but I'm stuck at this simple thing. I can't replicate the issue using CodePen so we're going to have to go for theories and suggestions. I'll try to be as specific as I can.

Adding this interval when the page loads to check when an input with the id serialNumberInput is available. Then I'm adding a dropdown to the form, and attach an onChange event to it to update the serial input field with the value of the selected option. However, the trigger parts just never happens. It does work when I enter them manually, but not with the script.

var populateSerialNumbersTimer = setInterval(function(){

    var serial = $("input#serialNumberInput");

    if($(serial).length >= 1){

        $(serial).css("display", "inline").css("width", "50%");
        $(serial).after(deviceToSerialSelectionHTML);

        $("select#deviceToSerial").on("change", function(){
            $(serial).val($("select#deviceToSerial").val());
            $(serial).trigger("change");
            $(serial).trigger("blur");

        });

        clearInterval(populateSerialNumbersTimer);
    }
}, 200);

I've thought about it and considering how the serial number ends up in the text field the field must be accessible. Maybe it's that the events that I'm trying to trigger has not been declared at the time of the function declaration?

Suggestions much appreciated.


回答1:


It looks like jQuery tries to cache the event somehow. This is how I solved it with native javascript in case someone else is interested:

function triggerEvent(e, s){
    "use strict";
    var event = document.createEvent('HTMLEvents');
    event.initEvent(e, true, true);
    document.querySelector(s).dispatchEvent(event);
}

$("select#deviceToSerial").on("change", function(){

    serialNumberInput.val($("select#deviceToSerial").val());

    triggerEvent("change", "input#serialNumberInput");
    triggerEvent("blur", "input#serialNumberInput");

}


来源:https://stackoverflow.com/questions/48729519/tampermonkey-trigger-event-does-not-work-for-element

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