【发布时间】:2012-08-07 00:57:36
【问题描述】:
我想编写一个 Chrome 扩展程序,它将在加载图像之前更改 img 元素的 src= 值。
我有更改图像的代码,但它总是在 img 加载后执行。如何在加载图像之前更改 SRC 中的 url?
【问题讨论】:
我想编写一个 Chrome 扩展程序,它将在加载图像之前更改 img 元素的 src= 值。
我有更改图像的代码,但它总是在 img 加载后执行。如何在加载图像之前更改 SRC 中的 url?
【问题讨论】:
你应该:
run_at 属性为document start。beforeload event handler 中。您的脚本应如下所示:
String.prototype.endsWith = function(str) {
return this.substr(str.length*-1) === str;;
};
function doBeforeLoad(event) {
// Check to see if its what you want to redirect
// You can check against different things about the element, such as its type (tagName), id, class, whatever
// Be aware that if your checking the src attribute and it was a relative path in the html then the src you recieve will be resolved....
// so if the html was <img src="/bunyip.png"> and the base url is www.google.com then the event.srcElement.src will be www.google.com/bunyip.png
// this is why I use the ends with...so you dont have to deal with things like http://www.google.com, https://www.gooogle.com, http://google.com
// We also check for a data attribute that we set, so we know its allready been redirected
// we do this because if you redirect a source it will fire another beforeload event for its new url
if (!event.srcElement.dataset['redirected'] && event.srcElement.tagName == "IMG" && event.srcElement.src.endsWith('/test.png')) {
// If it is something we want to redirect then set a data attribute so we know its allready been changed
// Set that attribute to it original src in case we need to know what it was later
event.srcElement.dataset['redirected'] = event.srcElement.src;
// Set the source to the new url you want the element to point to
event.srcElement.src = "replacement.png";
}
}
document.addEventListener('beforeload', doBeforeLoad, true);
【讨论】:
beforeload 事件应该用于此任务。如果我没有找到重复的问题,请将其作为答案发布。
beforeload 事件)是chrome.webRequest API(重定向图像)。这必须在后台页面中实现,如果某些图像总是需要重定向,则优先于beforeload。
如果您知道 url 模式,则可以使用 webRequest API-http://developer.chrome.com/extensions/webRequest.html 来阻止和重定向图像调用。但是这不会改变 src,你可以稍后再做。这甚至会阻止对该图像源的 GET 调用。
最初来自-How can I prevent loading from <img> via content script?
【讨论】:
看看Avoid jQuery (pre)loading images 或construct a DOM tree from a string without loading resources (specifically images)。不久前我遇到了这个问题,我的解决方案基本上是相同的(用 'blah=' 替换 html 字符串中的 src 属性,然后添加我自己的 src)。正如链接中所说,如果您使用的是 jquery,请不要使用 $(html),因为它一解析就会获取图像。
【讨论】:
<body> 元素,在其中插入我的html 字符串,然后使用querySelector?这并不过分冗长,但也不是$(str).find('img');。
<table>some naughty text<tr></tr></table> 的内容,Chrome 会将文本放在表格之外,因为它认为它不有效,它会无论如何,当它呈现它时做。一个简单的例子stackoverflow.com/a/10896868/189093