• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2013 The Chromium Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Common media action functions."""
6
7import logging
8import os
9
10from telemetry.core import util
11from telemetry.page.actions import page_action
12
13
14class MediaAction(page_action.PageAction):
15  def WillRunAction(self, tab):
16    """Loads the common media action JS code prior to running the action."""
17    self.LoadJS(tab, 'media_action.js')
18
19  def RunAction(self, tab):
20    super(MediaAction, self).RunAction(tab)
21
22  def LoadJS(self, tab, js_file_name):
23    """Loads and executes a JS file in the tab."""
24    with open(os.path.join(os.path.dirname(__file__), js_file_name)) as f:
25      js = f.read()
26      tab.ExecuteJavaScript(js)
27
28  def WaitForEvent(self, tab, selector, event_name, timeout):
29    """Halts media action until the selector's event is fired.
30
31    Args:
32      tab: The tab to check for event on.
33      selector: Media element selector.
34      event_name: Name of the event to check if fired or not.
35      timeout: Timeout to check for event, throws an exception if not fired.
36    """
37    util.WaitFor(lambda:
38                     self.HasEventCompletedOrError(tab, selector, event_name),
39                 timeout=timeout)
40
41  def HasEventCompletedOrError(self, tab, selector, event_name):
42    if tab.EvaluateJavaScript(
43        'window.__hasEventCompleted("%s", "%s");' % (selector, event_name)):
44      return True
45    error = tab.EvaluateJavaScript('window.__error')
46    if error:
47      logging.error('Detected media error while waiting for %s: %s', event_name,
48                    error)
49      return True
50    return False
51