我正在编写一个应用程序,应该嵌入特定的网站到一个<webview>
,并注入一些CSS和JS代码,以适应这个网站上查看某些触摸敏感的设备。
问题是,在加载页面时,我无法找到注入代码的方法,而是在呈现页面之后注入代码,结果,所有修改都变得可见。
虽然代码注入非常适合于chrome扩展和内容脚本(通过在run_at
上将document_end
属性设置为document_end
),但对于for视图则不是这样。
这是我的代码:
manifest.json
{
"name": "App",
"version": "0.0.1",
"manifest_version": 2,
"app": {
"background": {
"scripts": [ "main.js" ]
}
},
"permissions": [
"webview"
]
}
main.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', { state: "normal" },
function(win) {
win.contentWindow.onload = function() {
var wv = this.document.querySelector('webview');
wv.addEventListener('contentload', function(e) {
this.insertCSS({ code: "body { background: red !important; }" });
});
}
}
);
});
index.html
<webview src="https://developer.chrome.com/apps/tags/webview" style="width: 100%; height: 100%;"></webview>
在Gist上也是这样:https://gist.github.com/OnkelTem/ae6877d2d7b2bdfea5ae
如果你尝试这个应用程序,你会看到只有在网页视图被加载和完全渲染之后,我的CSS规则才会被应用,页面背景会变成红色。在本例中,我使用contentload webview事件,但我也尝试了所有其他webview事件:loadstart、loadstart、loadcommit --没有任何区别。
我也尝试过使用webview.contentWindow,但是这个对象一直是空的,尽管文献状态应该使用它。
有什么想法吗?有可能吗?
发布于 2014-11-09 13:10:55
其次,将runAt: 'document_start'
添加到webview.insertCSS
调用中(如果您想要使用它,这也适用于webview.executeScript
)。executeScript
的实现与扩展的executeScript实现共享,但不幸的是,应用文档不完整。看一看chrome.tabs.insertCSS
,直到修复了应用文档。
下面是一个按需要工作的示例:
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', { state: 'normal' },
function(win) {
win.contentWindow.onload = function() {
var wv = this.document.querySelector('webview');
// loadcommit instead of contentload:
wv.addEventListener('loadcommit', function(e) {
this.insertCSS({
code: 'body { background: red !important; }',
runAt: 'document_start' // and added this
});
});
}
}
);
});
注意:尽管前面做了一些工作,但我建议将操作webview的脚本放在index.html中,因为生成的代码要整洁得多。
// main.js
chrome.app.runtime.onLaunched.addListener(function() {
chrome.app.window.create('index.html', { state: 'normal' });
});
<!-- index.html -->
<webview src="https://developer.chrome.com/apps/tags/webview" style="width: 100%; height: 100%;"></webview>
<script src="index.js"></script>
// index.js
var wv = document.querySelector('webview');
wv.addEventListener('loadcommit', function() {
wv.insertCSS({
code: 'body { background: red !important; }',
runAt: 'document_start'
});
});
https://stackoverflow.com/questions/26832848
复制