user1566059
user1566059

Reputation: 13

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

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?

Upvotes: 1

Views: 976

Answers (2)

Brandon
Brandon

Reputation: 284

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.

Upvotes: 0

Brock Adams
Brock Adams

Reputation: 93483

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.

Upvotes: 1

Related Questions