我正在创建一个需要注入浮动元素的chrome扩展(即position:fixed
)
在页面底部。我的要求是:
到目前为止,我已经尝试了三种解决方案并且没有提出任何建议。
内容脚本注入固定的html元素 这个解决方案的问题是页面的样式和我的元素的样式会相互影响,从而导致网页影响我的元素的样式,反之亦然。
内容脚本注入iframe
这里的问题是无法从创建iframe的内容脚本访问iframe中的元素,另一方面,chrome扩展不允许在动态注入的iframe中运行内容脚本(即使使用all_frames: true
时)。
扩展开发工具面板
这不符合我的需要,因为我需要在每个页面上显示我的面板。例如,用户可以预先形成一个操作,该操作打开多个选项卡并使所有选项卡都具有我的元素。在devtool面板中,我的用户必须手动在所有选项卡中打开devtoold。
请告知。
答案 0 :(得分:19)
有关3种方法的建议
是的,如果指定的样式在网页中过于通用
例如:
div {
border:none;
}
确实会影响内容脚本(s)元素,即使你将id和s的罕见组合分配给css,解决方案是使用css指定(或)覆盖所有样式,这非常麻烦
Ex:超越每种容易出错且繁琐的风格。
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
我建议这是关于动态iframe脚本注入问题的最佳方法;是的,可以将脚本注入动态生成的iframe
{
"name": "Iframe",
"description": "",
"version": "1",
"manifest_version": 2,
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"myscript.js"
],
"run_at": "document_end"
},
{
"matches": [
"<all_urls>"
],
"js": [
"anotherscript.js"
],
"all_frames": true
}
],
"permissions": [
"<all_urls>"
]
}
var iframe = document.createElement("iframe");
iframe.setAttribute("src", "https://www.facebook.com/plugins/like.php?href=http://allofrgb.blogspot.in/");
iframe.setAttribute("style", "border:none; width:150px; height:30px");
iframe.setAttribute("scrolling", "no");
iframe.setAttribute("frameborder", "0");
document.body.appendChild(iframe);
iframes = document.getElementsByTagName("iframe");
for (iframe in iframes){
console.log(iframes[iframe].src);
}
console.log("In another Script");
如果您观察到控制台记录的消息,您会观察到消息被记录两次(document
log + iframe
log + [any number of optional iframes in pages]*
)
anotherscript.js
个状态期间运行的 document idle
会在动态生成的iframe中执行,您可以随时通过chrome.tabs.executeScript()重新运行内容脚本。
您已明确发现问题,因此将其作为替代方案取消。
答案 1 :(得分:-9)
正如Sudarshan评论的那样,iframe是最好的做法。
为了在iframe中运行脚本,我只是在我的插件中包含iframe.html和script.js。在我的内容脚本中,我得到了chrome.extension.getURL('iframe.html')
的iframe(只有后台脚本可以访问此API,因此我使用Message Passing)脚本作为iframe中的相对脚本标记包含在内,如下所示:{{1} }
对我来说,令人惊讶的部分是虽然script.js没有包含在清单中,但它仍然可以访问chrome api,更重要的是在我的情况下,将消息发送到后台脚本。