无法在Chrome扩展程序中使用jQuery触发点击

无法在Chrome扩展程序中使用jQuery触发点击

本文介绍了无法在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);
});

manifest.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触发点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:27