How to run content script of google chrome extension after all the dom is created

StackOverflow https://stackoverflow.com/questions/11742774

  •  23-06-2021
  •  | 
  •  

سؤال

I have a google chrome extension which need to get a video URL from the dom

var videolink = document.getElementsByTagName('video')[0].attributes.getNamedItem('src').nodeValue;

I found video element is created by javascript after the page is loaded. So I try to run the content script above in phase "document_idle". But seems the video element isn't initalized even then.

Is there any way I can use to run content script later then the video element be initalized?

هل كانت مفيدة؟

المحلول

The simplest, most robust, way to handle elements created/loaded by javascript, is to poll for them:

var waitForVideo = setInterval (checkForElement, 150);

function checkForElement () {
    var videoElem       = document.getElementsByTagName ('video');
    if (videoElem.length) {
        clearInterval (waitForVideo);
        var videolink   = videoElem[0].getAttribute ('src');
        // DO WHATEVER, WITH videolink HERE.
    }
}

Alternatively, you could try the brand-new DOM Mutation Observers, but these were just added to Firefox and Chrome, and are probably overkill in this instance.

نصائح أخرى

If you can edit the page in your extension, you should be able to add a onLoad=yourFunction() attribute to the element so that it will call your function once the element is ready.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top