0

extension script:

function newtab() {
    chrome.tabs.create({"url":domain,"selected":true}, function(tab) {
        //--
    });
}

In my extension script I am opening a new tab with some domain. I want to be able to check if the dom in that new tab is loaded and then execute some operations on the dom in the new tab.

I checked the chrome extension documentation but could not find any appropriate method to achieve it.

Be my guiding light please.

Ninja Turtle
  • 156
  • 2
  • 18
  • Use [chrome.tabs.executeScript](https://developer.chrome.com/extensions/tabs#method-executeScript). There many answers showcasing this method, so I think you can find plenty of examples. – wOxxOm Jul 17 '16 at 09:54
  • okay thanks @wOxxOm :) – Ninja Turtle Jul 17 '16 at 09:56
  • Example for a simple case: [How to check how many elements of a certain type has a page with Chrome Extension Dev](http://stackoverflow.com/a/30380827) – wOxxOm Jul 17 '16 at 10:21
  • Possible duplicate of [Chrome extension create new tab and send message from popup.js to content script of new tab](http://stackoverflow.com/questions/38296583/chrome-extension-create-new-tab-and-send-message-from-popup-js-to-content-script) – Haibara Ai Jul 18 '16 at 01:41

1 Answers1

1

Content Scripts are the only part of the extension that can access/modify the DOM.

You can use the so-called Programmatic Injection to add a content script to the newly opened tab:

function newtab() {
    chrome.tabs.create({"url":domain,"selected":true}, function(tab) {
        chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
    });
}

.executeScript() is subject to run_at parameter, that defaults to document_idle. This guarantees that the script will only execute after static DOM is completely loaded.

In case of dynamic DOM (page's scripts create more DOM after the static content has loaded), even defining "tab is loaded" state is problematic. Listening to DOM changes can help you.

A couple of notes:

  • Programmatic Injection into a new page requires host permissions for the page. You would need a broad permission such as "*://*/*" or "<all_urls>" if you do not know the domain in advance.
  • "document_idle" does not guarantee that all resources are loaded, e.g. an <img> tag may already exist but the image is not yet loaded. See the run_at documentation for details and advice.
  • You can use a callback for .executeScript(), which may be the simplest way to pass some reply back to the script, but make sure you understand the signature of the expected callback.
Xan
  • 74,770
  • 16
  • 179
  • 206