在内容脚本中使用jQuery获取DOM对象失败

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

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(内容脚本):

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

jQuery使用类似CSS的选择器 。

要按ID选择元素 ,您需要使用#。 此外,jQuery总是返回一个结果数组,即使它是唯一的。

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

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

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

还有其他function来处理元素的类 。

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

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

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

 // 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; } 

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

 function logger(node) { console.log(node.className); } var observer = watchNodes("#gwt-uid-115", logger); 

或者,例如,如果要捕获id为以gwt-uid开头的所有节点,则可以编写自定义filter:

 function filter(node) { if(node.id && node.id.match(/^gwt-uid/)) return true; else return false; } var observer2 = watchNodes(filter, logger); 

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

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