在内容脚本中使用jQuery获取DOM对象失败 [英] Getting DOM object fails with jQuery in content script

查看:198
本文介绍了在内容脚本中使用jQuery获取DOM对象失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google页面中有一个按钮。 DOM Inspector提供其ID。但是尝试获取对象失败。当绑定在控制台中写入它的类名时,我得到未定义的结果。在页面中只有一个iframe,而我的对象不在里面(据我所知)。


$ b

manifest.json

  {
manifest_version:2,
name:修改字符串,
description:批量修改字符串,
version:1.0,
permissions:[
tabs,
history,
http:// * / *,
https:// * / *
],

content_scripts:[
{
匹配:[https://play.google.com/apps/*],
js:[jquery-1.11.1.min.js,myInject.js ],
all_frames:true
}
],

web_accessible_resources:[
script.js,
jquery-1.11.1.min.js
],

browser_action:{
default_icon:icon.png,
default_popup :popup.html




}

myInject.js(content script):

  var buttonJGET = jQuery(gwt-uid-115 ,文件); 
console.log(buttonJGET.className);


解决方案

jQuery使用类CSS选择器



通过它的id选择元素,你需要使用#。
此外,jQuery总是返回结果数组,即使它是唯一的。



$ p $ var buttonJGET = jQuery( #GWT-UID-115\" )[0];






jQuery元素不同于DOM元素;他们没有 className 属性。
为了得到它,可以使用,例如:

  console.log(buttonJGET.attr('class' )); 

还有处理元素类的其他函数

否则,您可以从jQuery元素中提取DOM元素

  var buttonJGET = jQuery(#gwt-uid-115)。get(0); 
console.log(buttonJGET.className);






如果代码仍然失败,可能是因为在脚本运行的那一刻,没有具有该id的元素(还)。为了实现每次添加元素时运行我的代码,可以使用 DOM变异观察者(规范答案此处):

  //为每个添加的DOM元素匹配一个过滤器运行一个函数
// filter - 两个函数(DOM_node){/ *。 .. * /},返回true或false
//或者一个jQuery选择器
//回调函数(DOM_node){/*...*/}
函数watchNodes(filter ,回调){
var observer = new MutationObserver(function(mutations){
mutations.forEach(function(mutation){
if(typeof filter ===function){
$(mutation.addedNodes).filter(
function(i){return filter(this);}
).each(
function(i){callback(this);}
);
} else {
$(mutation.addedNodes).f ilter(filter).each(
function(i){callback(this); }
);
}
});
});

//对于每个添加的元素,突变将被处理
// with mutation.taget ==父
//和包含添加元素的mutation.addedNodes
observer.observe(document,{subtree:true,childList:true});

返回观察者;

$ / code>

使用(注意,过滤器和回调使用DOM元素):

 函数记录器(节点){
console.log(node.className);
}

var observer = watchNodes(#gwt-uid-115,logger);

或者,例如,如果您想要捕获以<$ c $开头的所有节点c> gwt-uid ,您可以编写自定义过滤器:

  function filter(node){ 
if(node.id&& node.id.match(/ ^ gwt-uid /))返回true;
else返回false;
}

var observer2 = watchNodes(filter,logger);

注入 run_at:document_start将确保您将捕获添加的所有元素。



要停止观察,请在> observer.disconnect()上调用返回观察者对象。


I have a button in a google page. DOM Inspector gives its id. However trying to obtain the object fails. I get an undefined result while tying to write its class name in the console. There's only one iframe in the page and my object is not inside it (as far as I know).

manifest.json:

{
    "manifest_version": 2,
    "name": "modify strings",
    "description": "modify strings in bulk",
    "version": "1.0",
    "permissions": [
       "tabs",
       "history",
       "http://*/*",
       "https://*/*"
    ],  

    "content_scripts": [
        {
            "matches": ["https://play.google.com/apps/*"],
            "js": ["jquery-1.11.1.min.js", "myInject.js"],
            "all_frames": true
        }
    ],

    "web_accessible_resources": [
        "script.js",
        "jquery-1.11.1.min.js"
    ],

    "browser_action": {
        "default_icon": "icon.png",
        "default_popup": "popup.html"
    }



}

myInject.js (content script):

var buttonJGET = jQuery("gwt-uid-115", document);   
console.log(buttonJGET.className);

解决方案

jQuery uses CSS-like selectors.

To select element by its id, you need to use #. Also, jQuery always returns an array of results, even if it is unique.

var buttonJGET = jQuery("#gwt-uid-115")[0];


jQuery elements are different from DOM elements; they do not have className attribute. To get it, one can use, for instance:

console.log(buttonJGET.attr('class'));

There are also other functions to deal with elements' classes.

Otherwise, you can extract a DOM element out of a jQuery element:

var buttonJGET = jQuery("#gwt-uid-115").get(0);
console.log(buttonJGET.className);


If the code still fails, it might be because at the moment the script is run there is no element with that id (yet). To achieve "run my code every time such an element is added", one can use DOM mutation observers (canonical answer here):

// Runs a function for every added DOM element that matches a filter
// filter -- either function(DOM_node){/*...*/}, returns true or false 
//           OR a jQuery selector
// callback -- function(DOM_node){/*...*/}
function watchNodes(filter, callback){
  var observer = new MutationObserver( function (mutations) {
    mutations.forEach( function (mutation){
      if(typeof filter === "function"){
        $(mutation.addedNodes).filter(
          function(i){ return filter(this); }
        ).each(
          function(i){ callback(this); }
        );
      } else {
        $(mutation.addedNodes).filter(filter).each(
          function(i){ callback(this); }
        );
      }
    });
  });

  // For every added element, a mutation will be processed
  //   with mutation.taget == parent
  //   and mutation.addedNodes containing the added element
  observer.observe(document, { subtree: true, childList: true });

  return observer;
}

To use (note, filter and callback use DOM elements):

function logger(node) {
  console.log(node.className); 
}

var observer = watchNodes("#gwt-uid-115", logger);

Or, if, for instance, you want to catch all nodes whose id's start with gwt-uid, you can write a custom filter:

function filter(node) {
  if(node.id && node.id.match(/^gwt-uid/)) return true;
  else return false;
}

var observer2 = watchNodes(filter, logger);

Injecting this at run_at: "document_start" will ensure you'll capture all elements added.

To stop observing, call observer.disconnect() on the returned observer object.

这篇关于在内容脚本中使用jQuery获取DOM对象失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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