1

我想编写一个 Chrome 扩展程序,它将在加载图像之前更改 img 元素的 src= 值。

我有更改图像的代码,但它总是在 img 加载后执行。如何在加载图像之前更改 SRC 中的 url?

4

3 回答 3

4

你应该:

  1. 确保run_at内容脚本的属性是document start.
  2. 将您的图像重写代码放在beforeload事件处理程序中。

您的脚本应如下所示:

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);
于 2012-08-07T01:36:10.427 回答
1

如果您知道 url 模式,则可以使用 webRequest API- http://developer.chrome.com/extensions/webRequest.html来阻止和重定向图像调用。但是这不会改变 src,你可以稍后再做。这甚至会阻止对该图像源的 GET 调用。

最初来自 -如何防止通过内容脚本从 <img> 加载?

于 2013-10-28T10:00:30.600 回答
0

看看避免 jQuery(预)加载图像从字符串构造 DOM 树而不加载资源(特别是图像)。不久前我遇到了这个问题,我的解决方案基本上是相同的(用 'blah=' 替换 html 字符串中的 src 属性,然后添加我自己的 src)。正如链接中所说,如果您使用的是 jquery,请不要使用$(html),因为它一解析就会获取图像。

于 2012-08-07T01:13:10.050 回答