Why doesn't this JQuery event to fire in gmail?

北城以北 提交于 2019-12-02 01:39:08
Rob W

Most DOM events, including the click event are dispatched as follows:

  1. Capture phase (from document(window, document, document.documentElement, ...) down the tree to the clicked element).
  2. Bubble phase (from the clicked element up the tree to document ..., window).

Events bound with jQuery are always triggered in #2, at the bubbling phase. Gmail appears to bind an event add capture phase, and calls event.stopPropagation(); when the user clicks on <a> elements. This methods stops the propagation of the event, so jQuery will never know about the event because #2 never occurs.

So, drop jQuery and use vanilla JavaScript to bind the event:

document.addEventListener('click', function(event) {
    // Do whatever you want
}, true);

By setting the third argument of addEventListener to true, the listener is triggered at capture phase.


Regarding the jQuery error (from the question):
Gmail doesn't load jQuery, so you cannot use it. Usually, you would get ReferenceError: "$ is not defined". Instead, you saw "TypeError: Object # has no method 'on'", because $ is defined as a shorthand for document.querySelector in Chrome's developer tools when the page doesn't declare $.

If you included jQuery with your extension, it can be used by switching to the appropriate context. For more details, see Why will jQuery not load in Facebook?

I poked around what gmail is loading, and it appears that gmail doesn't load jquery.

Not all websites use jQuery. If you want to have access to a specific jQuery library version you're going to need to load that so you have access to it in your extension.

So I tested it, and it works just fine. Like I said in my comment, you need to inject jQuery yourself in all cases. You cannot access the page's javascript, nor any javascript from other extensions. Some example code:

manifest.json

{
  "name": "Gmail jQuery Test",
  "version": "0.1",
  "description": "Gmail jQuery Test",
  "manifest_version": 2,
  "permissions": [
    "https://mail.google.com/*"
  ],
  "content_scripts": [{
    "matches": ["https://mail.google.com/*"],
    "js": ["jquery.js", "script.js"],
    "all_frames": true
  }]
}

script.js

$('body').on('click', function(event) {
  console.log("Entered function");
});

This shows the message on the inbox page, and inside of any message and other pages.

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