Search code examples
javascriptgoogle-chromedomgoogle-chrome-extension

How can i change source code any webpage with chrome extension?


I am trying make a my own chrome extension. Yes i did it. But there is a problem with change html dom with javascript. i cant change source code. it works only web page interface.. I need to see my new html tags when i clicked the source code.


Solution

  • No. You can't change "source code", or at least, not like the way you can do so with the DOM.

    The view source views the raw data (in this case, code) sent back from the source (hence known as "source code").

    To view changes, you have to open devtools and go to "elements", or use an extension that views the rendered source, like this extension.

    The source code is "static" (by static I mean, not changing even after the webpage is rendered and mutated. Technically, the server can send a different response as it wishes, but for this scenario we'll say it's "static"). It does not change like the DOM does. The source code is rendered by the browser into a webpage, which you can then access the DOM via scripts, or devtools. The source code is just raw data, you can't "change it" like you can with the DOM. Here's a good SO Q/A that shows you the difference between the DOM and the source code: What is the difference between source code and DOM?

    What you can do, though, is mutate the request via the chrome.webRequest, which I believe allows you to also mutate request responses (basically turning your extension into a proxy).

    Read more about chrome.webRequest here: https://developer.chrome.com/docs/extensions/reference/webRequest/