Home > Back-end >  Parsing data from dynamic webpage with injected content script
Parsing data from dynamic webpage with injected content script

Time:10-18

I'm trying to inject an iframe with my chrome extension and I'm having difficulty injecting it on a particular site. If I check the Network tab in chrome I can see that the main file looks something like this:

<body>
     <app-root></app-root>
     <script src="runtime.2ed1a126f5b940f24835.js" defer></script><script src="polyfills-es5.71c81a25540b98493cde.js" nomodule defer></script><script src="polyfills.6ff9102ee8a3b26f6c56.js" defer></script><script src="scripts.8b70b835e8cebce8bff7.js" defer></script><script src="main.be986289c2a19031ee6d.js" defer></script></body>
</html>

But if I inspect element(F12) the webpage after a second the source code of the page looks entierly different. Something like this:

<body >
     <app-root _nghost-hna-c0="" ng-version="8.2.14">
          <router-outlet _ngcontent-hna-c0=""></router-outlet>
          <app-home >
               <div ><app-header>
etc...

My injection code works on a page that is written in pure html but not on this one since it dynamically loads and updates the DOM? I see in console that it prints null when I try to grab a particular element via getElementByXpath. Can I somehow wait until it's finished loading(I'm guessing not since it's done at runtime) and then inject the code or is there a particular API endpoint that I could use.

My current code that works on normal html pages but not this particular dynamic one:

function Inject(width, height){
    var path = document.getElementsByClassName("content-box");
    path.insertAdjacentHTML("beforeBegin", '<div ><a href="https://somelink.com?width="   width   "&height="   height>Quick Connect</a></div>');
}

Thanks for the help, Sick

CodePudding user response:

function Inject(width, height){
  var bo = document.body;
  let html = '<div ><a href="https://somelink.com?width="'   width   '"&height="'   height   '">Quick Connect</a></div>';
  bo.insertAdjacentHTML("beforeBegin", html);
}
Inject(200,100);

CodePudding user response:

This is a sample MutationObserver.

matches.js

const onMutation = (mutations) => {
  mo.disconnect();

  for (const { addedNodes } of mutations) {
    for (const node of addedNodes) {
      if (node.className == "content-box") {
        node.insertAdjacentHTML("beforeBegin", "<div>hoge</div>");
      }
    }
  }

  observe();
}

const observe = () => {
  mo.observe(document, {
    subtree: true,
    childList: true,
  });
}

const mo = new MutationObserver(onMutation);

observe();

manifest.json

{
  "name": "MutationObserver",
  "version": "1.0",
  "manifest_version": 3,
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "matches.js"
      ]
    }
  ]
}
  • Related