禁用提交表单jquery的提交输入

时间:2015-11-20 19:00:07

标签: javascript jquery google-chrome-extension

我正在实现像chrome扩展一样的密码管理器,它会检测密码字段并尝试拦截提交功能。我想要的是:

  1. 用户点击"登录"在一个网站(比如Facebook)。扩展内容脚本检测密码和用户名
  2. 的值
  3. 询问用户是否要将登录凭据存储在管理器中
  4. 如果是,请存储凭据。
  5. 问题出在第2步,我试图阻止它提交,直到对话框返回用户操作,就像任何其他浏览器内置密码管理器一样。但显然preventDefault()不起作用,因为网页保持刷新就像调用curSubmit [0] .click()一样,这会使对话框不断重现。

    有什么问题吗?我的部分代码是:

    var inputs = document.getElementsByTagName("input");
    for (var i=0; i<inputs.length; i++) {
      if (inputs[i].type.toLowerCase() === "password") {
        var curSubmit = $("input[type=submit]",inputs[i].closest('form'));
        curSubmit[0].click(function(event){
          event.preventDefault();
        });
    
        curSubmit[0].onclick = function(){
           $('body').append('<div id="store-dialog" title="Store password?"><p>Do you want to store the login credentials?</p></div>');
           var buttons = $( ".store-dialog" ).dialog( "option", "buttons" );
           $( "#store-dialog" ).dialog({
              resizable: false,
              height: "auto",
              position: { my: "center", at: "center", of: window },
              modal: true,
              buttons: {
                "Yes": function() {
                  $( this ).dialog( "close" );
                },
                "Not this time": function() {
                  $( this ).dialog( "close" );
                },
                "Never": function() {
                  $( this ).dialog( "close" );
                }
              }
          });
        }
      }
      break;
    }
    

1 个答案:

答案 0 :(得分:0)

您用于click处理程序的语法无效,因为curSubmit[0]不是jQuery对象,而是标准DOM元素。

这些都是正确的:

  • curSubmit[0].onclick = function(e) { ...... };
  • curSubmit[0].addEventListener("click", function(e) { ...... });

至于停止尝试clicksubmit事件的整个火炮:

event.preventDefault();
event.stopPropagation();
event.stopImmediatePropagation();