0

I'm working on a chrome extension that will add some features to an existing page. But for that, I need to add a script to a page as soon as possible!! (No, I cannot simply run a content script that starts before everything, I need this particular script to be inserted into the DOM)

(Why? Because that page loads everythin using ajax calls, and I need to be able to perform some operations before those calls)

So I intent to add the script the sooner I can immediately after the head of the document appears.

I'm looking at MutationsObserver, and it seems it could do that job. But how can I check if a certain Node from the addedNodes collection is the head???

Kirill Slatin
  • 6,085
  • 3
  • 18
  • 38
Daniel Möller
  • 84,878
  • 18
  • 192
  • 214
  • 5
    look at the tagName of the node to see whether it is `HEAD` – Arun P Johny Jul 02 '15 at 04:25
  • You could also hook one of the `XMLHttpRequest` methods and catch things when the JS in the page tries to run its first ajax call. – jfriend00 Jul 02 '15 at 04:47
  • Thank you for your help.... I just found out that mutation observer just doesn't work at all..... – Daniel Möller Jul 02 '15 at 04:47
  • @jfriend00, that is **exactly** what I'm doing. And that is **precisely** the reason why I need to inject this script before any of those ajax calls (In a chrome extension, I'm unable to catch the requests if I don't inject the script **into the DOM**) – Daniel Möller Jul 02 '15 at 04:49
  • 1
    Maybe this: https://developer.chrome.com/extensions/webRequest – jfriend00 Jul 02 '15 at 04:54

1 Answers1

1

Since it looks like maybe this provided you an answer to your actual problem, I'll post it as an answer.

You can use the Chrome plug-in API to directly intercept the Ajax requests using this: https://developer.chrome.com/extensions/webRequest

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • This seems to be a pretty easy solution. But I tried it in my extension and `chrome.webRequest` is `undefined`. I added it to the manifest file as told in the documentation, but it doesn't seem to work. - The duplicate answer works though. The `documentElement` is present from the beginning and I can add the script into it. – Daniel Möller Jul 02 '15 at 05:20