我正在尝试创建一个突出显示预定义关键字的Chrome扩展程序。当页面内容是静态的但是我需要它的实际网站时,我能够使它工作,动态创建内容,我无法在那里工作。我不确定如何“监听”加载DOM后添加的新内容或如何修改它。我的最后一次尝试是使用MutationObserver,但它仍然无效。
这是我的第一次扩展,我对网络开发的了解非常有限。请不要嘲笑我明显的错误。 :)
的manifest.json:
{
"name": "Highlight Moderation Keywords",
"version": "0.1",
"permissions": ["http://*/*"],
"content_scripts": [
{
"matches": ["http://*/*","https://*/*"],
"js": ["jquery.js","jquery.highlight.js","highlightKeywords.js"],
"css" : ["highlight.css"],
"run_at": "document_end"
}
],
"manifest_version":2
}
这是在加载DOM后动态生成的HTML代码:
<div class="container-fluid">
<dl class="subject">
<dt>Review Rating</dt>
<dd class="rating">1</dd>
</dl>
<dl>
<dt>Text</dt>
<dd class="moderatable" data-fieldname="reviewText">This is a piece of crap. And the guy at customer service is an idiot.</dd>
</dl>
</div>
highlightKeywords.js:
// Highlight keywords as soon as page loads.
// I'm using a Jquery highlight plugin by bartaz/burkard.
// Maybe I don't even need these two lines??
$("body dd").highlight(["customer","service"], { element: 'em', className: 'kwd_CS' });
$("body dd").highlight(["crap","idiot"], { element: 'em', className: 'kwd_PRF' });
// The node to be monitored
var target = $(".container-fluid")[0];
// Create an observer instance
var observer = new MutationObserver(function( mutations ) {
mutations.forEach(function( mutation ) {
var newNodes = mutation.addedNodes; // DOM NodeList
if( newNodes !== null ) { // If there are new nodes added
var $nodes = $( newNodes ); // jQuery set
$nodes.each(function() {
var $node = $( this );
$("body dd").highlight(["customer","service"], { element: 'em', className: 'kwd_CS' });
$("body dd").highlight(["crap","idiot"], { element: 'em', className: 'kwd_PRF' });
});
}
});
});
// Configuration of the observer:
var config = {
attributes: true,
childList: true,
characterData: true
};
// Pass in the target node, as well as the observer options
observer.observe(target, config);
highlight.css:
.kwd_CS { background-color: #FFFF66; }
.kwd_PRF { background-color: #E06666; }
另一方面,我知道我可以将关键字数组添加为变量,我可能会因为它们有更多而且列表更长。我稍后会尝试,因为我不知道如何定义这些变量,所以Jquery会看到它们。
提前非常感谢你!