这是我一直遇到的一些困难.我有一个本地客户端脚本,需要允许用户获取远程网页并搜索结果页面的表单.为了做到这一点(没有正则表达式),我需要将文档解析为完全可遍历的DOM对象.
我想强调的一些限制:
getElementsByTagName需要提供DOM API等.假设我在变量中有一个完整的HTML文档字符串(包括DOCTYPE声明)html,这是我到目前为止所尝试的:
var frag = document.createDocumentFragment(),
div = frag.appendChild(document.createElement("div"));
div.outerHTML = html;
//-> results in an empty fragment
div.insertAdjacentHTML("afterEnd", html);
//-> HTML is not added to the fragment
div.innerHTML = html;
//-> Error (expected, but I tried it anyway)
var doc = new ActiveXObject("htmlfile");
doc.write(html);
doc.close();
//-> JavaScript executes
Run Code Online (Sandbox Code Playgroud)
我也尝试从HTML中提取<head>和<body>节点,并将它们添加到<HTML>片段内的元素,仍然没有运气.
有没有人有任何想法?
我正在编写一个chrome扩展,需要迭代注入页面中的所有样式表并修改某些样式.
我迭代/修改样式,例如:
const iterate = (doc, f) => {
for (const styleSheet of doc.styleSheets) {
const rules = styleSheet.rules || styleSheet.cssRules;
if (!rules) continue;
for (const cssRule of rules) {
if (!cssRule.style) continue;
const selector = cssRule.selectorText, style = cssRule.style;
if (!selector || !style.cssText) continue;
f(style);
}
}
}
document.addEventListener("DOMContentLoaded", e => {
setTimeout(() => {
iterate(document, style => {
if (style.getPropertyValue('background-color')) style.setProperty('background-color', 'yellow');
});
}, 1000);
});Run Code Online (Sandbox Code Playgroud)
div {
background-color: red;
}Run Code Online (Sandbox Code Playgroud)
<div>hello</div>Run Code Online (Sandbox Code Playgroud)
我遇到的问题是外部css似乎没有被包括在内.
例如,如果我将我的扩展注入stackoverflow.com,它具有:
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/all.css?v=cfd0b49a38a7"> …Run Code Online (Sandbox Code Playgroud) 我需要查看HTML字符串<img>并将src属性为相对地址的所有标记更改为绝对URL.所以这:
<img src="puppies.jpg">
Run Code Online (Sandbox Code Playgroud)
需要成为:
<img src="http://sitename.com/path/puppies.jpg">
Run Code Online (Sandbox Code Playgroud)
而忽略属性已经绝对的<img>标签src.
我正在使用PHP并假设我需要运行它preg_replace().救命!谢谢!
从节点,我想从外部网页获取所有图像网址(src来自img标签的属性).
我开始考虑phantonjs,但不喜欢它没有真正集成到节点(即它在外部进程中运行).
接下来,我尝试使用请求模块和cheerio.这很好用,除了我必须处理相对图像网址.例如
<img src='http//example.com/i.jpg'>
<img src='/i.jpg'>
<img src='i.jpg'>
<img src='../images/i.jpg'>
Run Code Online (Sandbox Code Playgroud)
我可以解决这个问题,但我想知道是否有更简单的方法?