1

画像が読み込まれる前に img 要素の src= 値を変更する Chrome 拡張機能を作成したいと考えています。

画像を変更するコードがありますが、画像が読み込まれた後に常に実行されます。画像が読み込まれる前に 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 ツリーを構築するをご覧ください。少し前にこれに遭遇しましたが、私の解決策は本質的に同じでした (html 文字列の src 属性を 'blah=' に置き換えてから、独自の src を追加します)。$(html)リンクにあるように、jquery を使用している場合は、解析するとすぐに画像が取得されるため、使用しないでください。

于 2012-08-07T01:13:10.050 に答える