无法在 Chrome 扩展程序中使用 jQuery 触发点击 [英] Can't trigger click with jQuery in a Chrome extension

查看:57
本文介绍了无法在 Chrome 扩展程序中使用 jQuery 触发点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一行 jQuery 代码制作 Chrome 扩展程序,但它不起作用.我正在尝试触发对元素的点击.

I am trying to make a Chrome extension with one line of jQuery code but it doesn't work. I'm trying to trigger a click on an element.

chrome的控制台根本没有显示任何错误,当我只在控制台中放入 jQuery 代码时,它工作正常.

The console of chrome doesn't show any error at all, and when I put ONLY the jQuery code in console it works fine.

我的代码:

content.js

$(document).ready(function() {
  $('.like_post:contains(Like)').click();
});

background.js

chrome.windows.getCurrent( function(currentWindow) {
  chrome.tabs.query({active: true, windowId: currentWindow.id}, function(activeTabs){
    chrome.tabs.executeScript(
      activeTabs[0].id, {file: 'jquery-2.1.3.min.js', allFrames: true}
    );
    chrome.tabs.executeScript(
      activeTabs[0].id, {file: 'content.js', allFrames: true}
    );
  });
  console.log(currentWindow.id);
});

ma​​nifest.json

{
  "name": "plugin name",
  "version": "0",
  "description": "What do I do as an extension",

  "manifest_version": 2,
  "browser_action": {
    "name": "project with jquery",
    "icons": ["icon.png"],
    "default_icon": "icon.png"
  },
  "content_scripts": [ {
    "js": [ "jquery-2.1.3.min.js", "background.js", "content.js" ],

    "matches": [ "http://*/*", "https://*/*"]
  }]
}

我还下载了 jquery-2.1.3.min.js 文件并将其放在扩展文件夹中.

I have also downloaded the jquery-2.1.3.min.js file and have it in the extension folder.

谁能解释为什么它不起作用???

Can anyone explain why it doesn't work???

推荐答案

问题的根本原因是扩展内容脚本在 孤立世界.这样做的原因之一是您的代码不会与页面的代码冲突:例如,您可以使用不同版本的 jQuery.

The root cause of the problem is that extension content scripts execute in an isolated world. One of the reasons for this is so that your code does not conflict with the page's code: for instance, you can use a different version of jQuery.

因此,您的内容脚本拥有自己的 jQuery 副本.jQuery 的 .click() 的工作方式是维护一个由点击触发的事件处理程序列表..

So, your content script has its own copy of jQuery. The way jQuery's .click() works is by maintaining a list of event handlers that are triggered by the click..

..你可能已经看到问题了.jQuery 的内容脚本副本不知道页面的处理程序副本列表,并且无法触发它们.

..and you may see the problem already. The content script's copy of jQuery is not aware of the page's copy list of handlers, and cannot trigger them.

顺便说一下,这解释了为什么当您将其放入控制台时它会起作用 - 默认情况下,控制台在页面的上下文中执行 并触发页面的 jQuery 副本.

That, by the way, explains why it works when you put it in the console - by default, console executes in the page's context and triggers the page's copy of jQuery.

有多种方法可以解决这个问题,但对您的任务来说,最直接的方法是发出一个正确 DOM 事件,该事件将被页面代码捕获.有关示例,请参阅此问题.

There are ways to overcome this, but the most straightforward for your task is to emit a proper DOM event, that will be caught by the page's code. See this question for an example.

这篇关于无法在 Chrome 扩展程序中使用 jQuery 触发点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆