首页 > 解决方案 > Intercept submit event

问题描述

I want to build a simple Google extensions that would stop users to submit a tweet if it contains a blacklisted word. This requires that I can intercept the click on "Tweet" that would submit it.

After inspecting the Twitter page, I currently use the following code in the content script:

$('button.tweet-action').click(function(e) {
  console.log(e);
  e.preventDefault();
  e.stopPropagation();
  return false;
});

When I click "Tweet" then I get the console output but the tweet is still submitted. Interestingly, when I use only $('button') then it works with many buttons. For example, I cannot delete a tweet anymore. So it kind of works just not for submitting new tweets, and I cannot tell why that's the case. Here's the snippet from Twitter HTML page:

enter image description here

How can I intercept and stop the submission of tweets.

Update: I've tried intercepting the form submit as suggest below. Since the form doesn't have an id, I used a class selector:

$('.tweet-form').submit(function(e) {
  console.log(e);
  e.preventDefault();
  e.stopPropagation();
  return false;
});

But it's not working. For a trivial test I tried $('.tweet-form').css(...) which successfully changed some style changes. However intercepting the submit doesn't work; I don't even see the console output. Maybe that's because there's no type="submit" anywhere between the form tags.

标签: javascriptjquerytwitter

解决方案


拦截按钮单击事件可stopImmediatePropagation()改为使用stopPropagation()。问题是这个按钮已经附加了一个点击处理程序,并且stopPropagation()只影响父事件处理程序。添加新的单击事件处理程序不会覆盖现有的事件处理程序。stopImmediatePropagation()防止调用同一事件的其他侦听器。

因此,工作解决方案如下所示:

$('button.tweet-action').click(function(e) {
  console.log(e);
  e.preventDefault();
  e.stopImmediatePropagation();
  return false;
});

推荐阅读