在加载图像之前更改chrome扩展中的<img/> SRC

时间:2012-08-07 00:57:37

标签: google-chrome-extension

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

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

3 个答案:

答案 0 :(得分:4)

你应该:

  1. 确保内容脚本的run_at属性为document start
  2. 将图片重写代码放在beforeload event handler
  3. 您的脚本应如下所示:

    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);
    

答案 1 :(得分:1)

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

最初来自 - How can I prevent loading from <img> via content script?

答案 2 :(得分:0)

查看Avoid jQuery (pre)loading imagesconstruct a DOM tree from a string without loading resources (specifically images)。我刚刚遇到这个问题,我的解决方案基本相同(用'blah ='替换html字符串中的src属性,然后添加我自己的src)。如链接中所述,如果您使用的是jquery,请不要使用$(html),因为只要它解析它就会获取图像。