0

I'm trying to change image src of DOM img object, but i have a problem with an image blinking when try to change it using chrome extention.

manifest.json

  "content_scripts": [{
  "js": ["./js/content.js"],
  "matches": ["*://example.com/*"],
  "run_at": "document_start"
}

content.js

var img = 'data:image/png;base64,.....'
var avatar = (document.getElementsByClassName('page_avatar_img'))[0];
avatar.src = img;

In this case, the extension waits for the DOM object to be created and only then replaces the original image to my img with blinking.

Can I change the text of an html document before creating a DOM object to avoid this and immediately create the object I need?

Change "run_at" on "document_start" in manifest.json did not help me, because chrome extention can't find an 'avatar' object.

Thank everyone for answers!

1 Answers1

1

You should look at chrome.webRequest.

Add the following code to your manifest.json:

{
    "name": "My extension",
    ...
    "permissions": [
      "<all_urls>",
      "webRequest",
      "webRequestBlocking"
    ],
    ...
  }

Then in background.js add the event listener:

chrome.webRequest.onBeforeRequest.addListener(
    function(details) {

      // some logic on change `details.url` to modified_url  

      return {redirectUrl: modified_url};
    },
    {urls: ["<all_urls>"]},
    ["blocking"]);

Don't forget also specify your background.js to manifest file:

"background": {
   "scripts": ["./background.js"],
   "persistent": true
}
  • This appears to have very little to do with the question. – Makyen Oct 22 '17 at 04:28
  • @Makyen, maybe, but this solves the specific problem with a replacing image's src and eliminates blinking. – Sergey Perfilev Oct 22 '17 at 10:35
  • Please provide more explanatory text in your answer. It was not clear to me that was what you were attempting to accomplish. Please also explain that this requires knowing, in advance of the request, the URL for the original image, not just it's element's `class`. Asking the OP if they want to *always* replace the resource in every page, or just in the one page, would help. Mentioning that this approach adds significant overhead to *every* webRequest would be a good idea. Another time, getting clarification from the OP that the problem meets the criteria needed for the solution would be good. – Makyen Oct 22 '17 at 18:26
  • While this might be a viable approach for a *very specific* subset of problems, without explanation and significant additional code, this could be taken out of context, which could result in causing other issues for both programmers and users. – Makyen Oct 22 '17 at 19:22
  • @Makyen, you're right. I'll clarify my answer a little bit later. Thank's for your review. – Sergey Perfilev Oct 23 '17 at 10:06