artoo chrome injection
=======================

This chrome content script injects artoo in every relevant page when the
artoo's extension is activated.
180522
function injectScript() {

    // Creating script element
    var script = document.createElement('script'),
        body = document.getElementsByTagName('body')[0];

    script.src = chrome.extension.getURL('build/artoo.chrome.js');
    script.type = 'text/javascript';
    script.id = 'artoo_injected_script';
    script.setAttribute('chrome', 'true');

    // Appending to body
    body.appendChild(script);
  }
20485
function contentLoaded(callback) {
    var addEventListener = doc['addEventListener'];
    var done = false, top = true,
        add = addEventListener ? 'addEventListener' : 'attachEvent',
        rem = addEventListener ? 'removeEventListener' : 'detachEvent',
        pre = addEventListener ? '' : 'on',

        init = function(e) {
          if (e.type == 'readystatechange' && doc.readyState != 'complete') {
            return;
          }
          (e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
          if (!done && (done = true)) { callback.call(win, e.type || e); }
        },

        poll = function() {
          try {
            root.doScroll('left');
          } catch(e) {
            win.setTimeout(poll, 50);
            return;
          }
          init('poll');
        };

    if (doc.readyState == 'complete') {
      callback.call(win, 'lazy');
    } else {
      if (doc.createEventObject && root.doScroll) {
        try { top = !win.frameElement; } catch(e) { }
        if (top) { poll(); }
      }
      doc[add](pre + 'DOMContentLoaded', init, false);
      doc[add](pre + 'readystatechange', init, false);
      win[add](pre + 'load', init, false);
    }
  }
1158538
def executescript(self, *args, **kwargs):
        

        with self:
            self._cursor.executescript(*args, **kwargs)
169866
function toggleInjectionForActiveTab() {
  var url = tabs.activeTab.url;
  if (!isInjectionEnabledForUrl(url)) {
    enableInjectionForUrl(url);
  } else {
    disableInjectionForUrl(url);
  }
}
263085
function() {
  /**
   * Current options values.
   * These are only ever modified by using the {@see #setOptions} call.
   * @type {!Options}
   * @private
   */
  this.options_ = new Options();

  /**
   * Page options JSON strings mapped by UUID.
   * These are used as a lookup for the HTTP header hack.
   * @type {!Object.<string>}
   * @private
   */
  this.pageOptionsBlobs_ = {};

  /**
   * Injected tabs, mapped by tab ID.
   * @type {!Object.<!InjectedTab>}
   * @private
   */
  this.injectedTabs_ = {};

  /**
   * Tracer.
   * @type {Tracer}
   * @private
   */
  this.tracer_ = null;

  /**
   * All popup window tab IDs mapped by opener tab ID.
   * @type {!Object.<number, number>}
   * @private
   */
  this.popupWindows_ = {};

  chrome.tabs.onActivated.addListener(
      this.tabActivated_.bind(this));
  chrome.tabs.onUpdated.addListener(
      this.tabUpdated_.bind(this));

  // Handle tab closes.
  chrome.tabs.onRemoved.addListener((function(tabId) {
    for (var key in this.popupWindows_) {
      if (this.popupWindows_[key] === tabId) {
        delete this.popupWindows_[key];
        break;
      }
    }
    if (tabId in this.injectedTabs_) {
      var injectedTab = this.injectedTabs_[tabId];
      this.injectedTabs_[tabId] = null;
      injectedTab.dispose();
    }
  }).bind(this));

  // Listen for commands from content scripts.
  chrome.extension.onConnect.addListener(function(port) {
    var options = this.getOptions();
    if (port.name == 'injector') {
      // Setup the extended info provider for the page.
      var tab = port.sender.tab;
      if (!tab) {
        // This sometimes happens on about:blank and the new tab page.
        return;
      }
      var pageUrl = URI.canonicalize(tab.url);
      var pageStatus = options.getPageStatus(pageUrl, tab.id);
      var pageOptions = options.getPageOptions(pageUrl);

      _gaq.push(['_trackEvent', 'extension', 'injected']);

      var injectedTab = new InjectedTab(
          this, tab, pageStatus, pageOptions, port);
      this.injectedTabs_[tab.id] = injectedTab;
    } else if (port.name == 'popup') {
      // Get info about the selected tab and send back.
      // Note: port.sender is the popup tab, not the current tab.
      chrome.tabs.getSelected(null, (function(tab) {
        var pageUrl = URI.canonicalize(tab.url);
        if (!pageUrl.length) {
          return;
        }
        this.sendPopupInfo_(pageUrl, tab.id, port);

        // Listen for messages from the popup.
        port.onMessage.addListener((function(data, port) {
          this.popupMessageReceived_(tab, data, port);
        }).bind(this));
      }).bind(this));
    }
  }.bind(this));

  // Detect the application.
  this.detectApplication_();
  var detectApplication = this.detectApplication_.bind(this);
  chrome.management.onInstalled.addListener(detectApplication);
  chrome.management.onUninstalled.addListener(detectApplication);
  chrome.management.onEnabled.addListener(detectApplication);
  chrome.management.onDisabled.addListener(detectApplication);

  // Rescan all open tabs to reload any that are whitelisted.
  this.options_.load(function() {
    var whitelist = this.options_.getWhitelistedPages();
    var whitelistMap = {};
    for (var n = 0; n < whitelist.length; n++) {
      whitelistMap[whitelist[n]] = true;
    }
    chrome.tabs.query({}, (function(tabs) {
      var tabsReloaded = 0;
      for (var n = 0; n < tabs.length; n++) {
        var pageUrl = URI.canonicalize(tabs[n].url);
        if (whitelistMap[pageUrl]) {
          tabsReloaded++;
          this.reloadTab(tabs[n].id, tabs[n].url);
        }
      }
      _gaq.push(['_trackEvent', 'extension', 'tabs_reloaded',
          null, tabsReloaded]);
    }).bind(this));
  }, this);

  // This hacky thing lets people open wtf from the omnibox.
  // HACK(benvanik): https://code.google.com/p/chromium/issues/detail?id=237817
  try {
    chrome.omnibox.setDefaultSuggestion({
      description: '<url><match>%s</match></url> Open trace file'
    });
  } catch (e) {
  }
  chrome.omnibox.onInputChanged.addListener((function(text, suggest) {
    suggest([
      {
        content: 'ui',
        description: 'Open the UI'
      }
    ]);
  }).bind(this));
  chrome.omnibox.onInputEntered.addListener((function(text) {
    chrome.tabs.getSelected(null, (function(tab) {
      text = text.trim();
      if (text == 'ui' || text.length == 0) {
        // Open the UI.
        _gaq.push(['_trackEvent', 'extension', 'omnibox_show_ui']);
        this.showUi_({
          targetTab: tab
        });
      } else {
        // A URL? File path? etc?
        if (text.indexOf('http') == 0) {
          _gaq.push(['_trackEvent', 'extension', 'omnibox_show_file']);
          this.showFileInUi_({
            targetTab: tab
          }, text);
        }
      }
    }).bind(this));
  }).bind(this));

  // FileBrowserHandler requests, on Chrome OS.
  if (chrome.fileBrowserHandler) {
    chrome.fileBrowserHandler.onExecute.addListener((function(id, details) {
      chrome.tabs.get(details.tab_id, (function(tab) {
        switch (id) {
          case 'open':
            this.showFileEntriesInUi_({
              targetTab: tab
            }, details.entries);
            break;
        }
      }).bind(this));
    }).bind(this));
  }

  // This is a workaround for a regression in Chrome that prevents blob URIs
  // from work in content scripts. Instead, we smuggle the options data
  // synchronously via HTTP headers. Yeah, I know. FML.
  // https://code.google.com/p/chromium/issues/detail?id=295829
  chrome.webRequest.onHeadersReceived.addListener((function(details) {
    var uuid = details.url.substr(details.url.lastIndexOf('/') + 1);
    var headerValue = this.pageOptionsBlobs_[uuid];
    return {
      responseHeaders: [
        {
          name: 'X-WTF-Options',
          value: headerValue
        }
      ]
    };
  }).bind(this), {
    urls: ['http://tracing-framework.appspot.com/tab-options/*'],
    types: ['xmlhttprequest']
  }, ['blocking']);
}
181402
function runScript(code) {
    var anchor = freeDefine ? define.amd : Benchmark,
        script = doc.createElement('script'),
        sibling = doc.getElementsByTagName('script')[0],
        parent = sibling.parentNode,
        prop = uid + 'runScript',
        prefix = '(' + (freeDefine ? 'define.amd.' : 'Benchmark.') + prop + '||function(){})();';

    // Firefox 2.0.0.2 cannot use script injection as intended because it executes
    // asynchronously, but that's OK because script injection is only used to avoid
    // the previously commented JaegerMonkey bug.
    try {
      // remove the inserted script *before* running the code to avoid differences
      // in the expected script element count/order of the document.
      script.appendChild(doc.createTextNode(prefix + code));
      anchor[prop] = function() { destroyElement(script); };
    } catch(e) {
      parent = parent.cloneNode(false);
      sibling = null;
      script.text = code;
    }
    parent.insertBefore(script, sibling);
    delete anchor[prop];
  }
382827
function inject() {
        if (!WIN || !needsInject) { return }
        needsInject = false;
        var style = Object.keys(byName)
          .map(function (k) { return byName[k]; })
          .concat(remainder).join('\n');
        /* istanbul ignore next */
        if (cssTextProp) { cssTextProp.cssText = style; }
        else { styleNode.innerHTML = style; }
      }
724478
function main() {

    // Triggering countermeasures
    artoo.emit('countermeasures');

    // Welcoming user
    if (artoo.settings.log.welcome)
      artoo.log.welcome();

    // Should we greet the user with a joyful beep?
    var beeping = artoo.settings.log.beeping;
    if (beeping)
      artoo.beep.greet();

    // Indicating we are injecting artoo from the chrome extension
    if (artoo.browser.chromeExtension)
      artoo.log.verbose('artoo has automatically been injected ' +
                        'by the chrome extension.');

    // If in phantom, dependencies are loaded synchronously
    if (artoo.browser.phantomjs) {
      artoo.$ = window.artooPhantomJQuery;
      delete window.artooPhantomJQuery;
      artoo.jquery.applyPlugins();
      return artoo.emit('ready');
    }


    // Injecting dependencies
    function injectJquery(cb) {
      artoo.jquery.inject(function() {

        // Applying jQuery plugins
        artoo.jquery.applyPlugins();

        cb();
      });
    }

    artoo.helpers.parallel(
      [injectJquery, artoo.deps._inject],
      function() {
        artoo.log.info('artoo is now good to go!');

        // Triggering exec
        if (artoo.settings.autoExec)
          artoo.exec();

        // Triggering ready
        artoo.emit('ready');
      }
    );

    // Updating artoo state
    artoo.loaded = true;
  }
1020323
protected function injectCSS() {
            if (!$this->isCLI && !self::$cssInjected) {
                self::$cssInjected = true;
                if (file_exists($this->config->cssPath)) {
                    echo '<style type="text/css">';
                    /** @noinspection PhpIncludeInspection */
                    include $this->config->cssPath;
                    echo '</style>';
                } else {
                    echo 'The AloFramework handlers\' CSS file could not be found: ' . $this->config->cssPath . PHP_EOL;
                }
            }
        }
1045825
function () {
		this._super.onconfigure ();
		var data = this.dom.qdoc ( "script[type='application/json']" );
		var json = JSON.parse ( data.textContent );
		var tree = this._maketree ( json );
		new dox.Tree ( tree ).output ();
	}
766511
function() {
		var self = this;

		// Create Dom elements
		this._el.content_item	= TL.Dom.create("div", "tl-media-item tl-media-documentcloud tl-media-shadow", this._el.content);
		this._el.content_item.id = TL.Util.unique_ID(7)

		// Check url
		if(this.data.url.match(/\.html$/)) {
		    this.data.url = this._transformURL(this.data.url);
		} else if(!(this.data.url.match(/.(json|js)$/))) {
		    trace("DOCUMENT CLOUD IN URL BUT INVALID SUFFIX");
		}

		// Load viewer API
        TL.Load.js([
					'https://assets.documentcloud.org/viewer/loader.js',
					'https://assets.documentcloud.org/viewer/viewer.js'],
            function() {	
	            self.createMedia();
			}
		);
	}
212853
function getScript(url, async, cb) {
    if (typeof async === 'function') {
      cb = async;
      async = false;
    }

    var el = document.createElement('script');

    // Script attributes
    el.type = 'text/javascript';
    el.src = url;

    // Should the script be loaded asynchronously?
    if (async)
      el.async = true;

    // Defining callbacks
    el.onload = el.onreadystatechange = function() {
      if ((!this.readyState ||
            this.readyState == 'loaded' ||
            this.readyState == 'complete')) {
        el.onload = el.onreadystatechange = null;

        // Removing element from head
        artoo.mountNode.removeChild(el);

        if (typeof cb === 'function')
          cb();
      }
    };

    // Appending the script to head
    artoo.mountNode.appendChild(el);
  }
193764
def fill_in_ckeditor(locator, opts)
      sleep 1
      content = opts.fetch(:with).to_json
      page.execute_script <<-SCRIPT
              CKEDITOR.instances['#{locator}'].setData(#{content});
                                                           $('textarea##{locator}').text(#{content});
      SCRIPT
    end
832281
private static void injectIntoFrames(final WebDriver driver, final String script, final ArrayList<WebElement> parents) {
		final JavascriptExecutor js = (JavascriptExecutor) driver;
		final List<WebElement> frames = driver.findElements(By.tagName("iframe"));

		for (WebElement frame : frames) {
			driver.switchTo().defaultContent();

			if (parents != null) {
				for (WebElement parent : parents) {
					driver.switchTo().frame(parent);
				}
			}

			driver.switchTo().frame(frame);
			js.executeScript(script);

			ArrayList<WebElement> localParents = (ArrayList<WebElement>) parents.clone();
			localParents.add(frame);

			injectIntoFrames(driver, script, localParents);
		}
	}
302274
function injectElementWithStyles( rule, callback, nodes, testnames ) {
    var mod = 'modernizr';
    var style;
    var ret;
    var node;
    var docOverflow;
    var div = createElement('div');
    var body = getBody();

    if ( parseInt(nodes, 10) ) {
      // In order not to give false positives we create a node for each test
      // This also allows the method to scale for unspecified uses
      while ( nodes-- ) {
        node = createElement('div');
        node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
        div.appendChild(node);
      }
    }

    // <style> elements in IE6-9 are considered 'NoScope' elements and therefore will be removed
    // when injected with innerHTML. To get around this you need to prepend the 'NoScope' element
    // with a 'scoped' element, in our case the soft-hyphen entity as it won't mess with our measurements.
    // msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx
    // Documents served as xml will throw if using &shy; so use xml friendly encoded version. See issue #277
    style = ['&#173;','<style id="s', mod, '">', rule, '</style>'].join('');
    div.id = mod;
    // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
    // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
    (!body.fake ? div : body).innerHTML += style;
    body.appendChild(div);
    if ( body.fake ) {
      //avoid crashing IE8, if background image is used
      body.style.background = '';
      //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
      body.style.overflow = 'hidden';
      docOverflow = docElement.style.overflow;
      docElement.style.overflow = 'hidden';
      docElement.appendChild(body);
    }

    ret = callback(div, rule);
    // If this is done after page load we don't want to remove the body so check if body exists
    if ( body.fake ) {
      body.parentNode.removeChild(body);
      docElement.style.overflow = docOverflow;
      // Trigger layout so kinetic scrolling isn't disabled in iOS6+
      docElement.offsetHeight;
    } else {
      div.parentNode.removeChild(div);
    }

    return !!ret;

  }
866999
function injectReporter() {
  page.evaluate(function (script) {
    function print(msg) {
      console.log(msg);
    }

    function onComplete(passed) {
      window.callPhantom(passed);
    }

    eval(script);

    var reporter = new ConsoleReporter();
    reporter.setOptions({
      print: print,
      printDeprecation: print,
      showColors: true,
      onComplete: onComplete
    });

    jasmine.getEnv().addReporter(reporter);
  }, reporterScript);
}
1016043
function( contents ) {
			if ( contents.requiredContent && !this._.editor.filter.check( contents.requiredContent ) )
				return;

			var pageHtml = [],
				titleHtml = contents.label ? ' title="' + CKEDITOR.tools.htmlEncode( contents.label ) + '"' : '',
				elements = contents.elements,
				vbox = CKEDITOR.dialog._.uiElementBuilders.vbox.build( this, {
					type: 'vbox',
					className: 'cke_dialog_page_contents',
					children: contents.elements,
					expand: !!contents.expand,
					padding: contents.padding,
					style: contents.style || 'width: 100%;'
				}, pageHtml );

			var contentMap = this._.contents[ contents.id ] = {},
				cursor,
				children = vbox.getChild(),
				enabledFields = 0;

			while ( ( cursor = children.shift() ) ) {
				// Count all allowed fields.
				if ( !cursor.notAllowed && cursor.type != 'hbox' && cursor.type != 'vbox' )
					enabledFields++;

				contentMap[ cursor.id ] = cursor;
				if ( typeof( cursor.getChild ) == 'function' )
					children.push.apply( children, cursor.getChild() );
			}

			// If all fields are disabled (because they are not allowed) hide this tab.
			if ( !enabledFields )
				contents.hidden = true;

			// Create the HTML for the tab and the content block.
			var page = CKEDITOR.dom.element.createFromHtml( pageHtml.join( '' ) );
			page.setAttribute( 'role', 'tabpanel' );

			var env = CKEDITOR.env;
			var tabId = 'cke_' + contents.id + '_' + CKEDITOR.tools.getNextNumber(),
				tab = CKEDITOR.dom.element.createFromHtml( [
					'<a class="cke_dialog_tab"',
						( this._.pageCount > 0 ? ' cke_last' : 'cke_first' ),
						titleHtml,
						( !!contents.hidden ? ' style="display:none"' : '' ),
						' id="', tabId, '"',
						env.gecko && !env.hc ? '' : ' href="javascript:void(0)"',
						' tabIndex="-1"',
						' hidefocus="true"',
						' role="tab">',
							contents.label,
					'</a>'
					].join( '' ) );

			page.setAttribute( 'aria-labelledby', tabId );

			// Take records for the tabs and elements created.
			this._.tabs[ contents.id ] = [ tab, page ];
			this._.tabIdList.push( contents.id );
			!contents.hidden && this._.pageCount++;
			this._.lastTab = tab;
			this.updateStyle();

			// Attach the DOM nodes.

			page.setAttribute( 'name', contents.id );
			page.appendTo( this.parts.contents );

			tab.unselectable();
			this.parts.tabs.append( tab );

			// Add access key handlers if access key is defined.
			if ( contents.accessKey ) {
				registerAccessKey( this, this, 'CTRL+' + contents.accessKey, tabAccessKeyDown, tabAccessKeyUp );
				this._.accessKeyMap[ 'CTRL+' + contents.accessKey ] = contents.id;
			}
		}