我想在谷歌阅读器上做一个 chrome 扩展,我发现了一个问题。内容脚本无法访问 iframe。对于所有 n,window.frames[n] = undefined。我在 manifest.json 中有这个“all_frames”:true。或者有人可以告诉我如何在每篇文章下添加一个按钮。谢谢!
1 回答
通过快速查看 Google Reader 呈现的 HTML,IFRAME 中的唯一按钮似乎是 Google Plus +1 按钮 - 所有其他按钮都不在 IFRAME 中。因此,您无需担心 IFRAME。
我假设现有按钮是出现在每篇文章下方的按钮:+1、分享、电子邮件、保持未读、添加标签。
如果您想向现有文章按钮添加一个新按钮,您需要做的就是枚举 DOM - 特别是“entry-actions”DIV 类,并在每篇文章中附加一个带有元素/按钮的新 SPAN。
我怀疑(但不确定)Reader 可能会用新文章动态更新 DOM。如果是这种情况,您可能需要跟踪添加到 DOM 的新文章,以便再次添加按钮。为此,为 DOMNodeInserted 添加一个事件侦听器 - 例如
document.addEventListener('DOMNodeInserted', onNodeInserted, false);
更新:
您看不到“.entry-actions”类的原因是因为它是动态添加的。
这是一个非常基本的工作示例。这将监视 DOM,当它看到没有我们的“.myclass” SPAN 按钮的 entry-actions DIV 时,将添加它。
您需要在扩展中包含 jquery 才能使其正常工作。我在这个例子中使用了 jquery-1.7.1.min.js。如果您剪切并粘贴示例,您还需要一个名为 foo.png 的图标文件。
清单.json
{
// Required
"name": "Foo Extension",
"version": "0.0.1",
// Recommended
"description": "A plain text description",
"icons": { "48": "foo.png" },
//"default_locale": "en",
// Pick one (or none)
"browser_action": {
"default_icon": "Foo.png", // optional
"default_title": "Foo Extension" // optional; shown in tooltip
},
"permissions": [ "http://*/", "https://*/", "tabs" ],
"content_scripts": [
{
"matches": ["http://*/*", "https://*/*"],
"js": ["jquery-1.7.1.min.js", "content_script.js" ],
"run_at": "document_idle"
}
]
}
content_script.js
var timer;
document.addEventListener('DOMNodeInserted', onNodeInserted, false);
function onNodeInserted(e)
{
if(timer) clearTimeout(timer);
timer = setTimeout("addButtons()", 250);
}
function addButtons()
{
console.log('add buttons');
var $actions = $(".entry-actions").filter(function() {
return $(this).find('.myclass').length === 0;
});
$actions.append('<span class="myclass"><a href="javascript:alert(\'hey! Im a foo extension injected button!\');return false;">My button</a></span>');
}