1#!/usr/bin/env python 2# Copyright (c) 2011 The Chromium Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6import os 7import sys 8import unittest 9 10import pyauto_functional 11from pyauto import PyUITest 12 13 14class ExecuteJavascriptTest(PyUITest): 15 def _GetExtensionInfoById(self, extensions, id): 16 for x in extensions: 17 if x['id'] == id: 18 return x 19 return None 20 21 def testExecuteJavascript(self): 22 self.NavigateToURL(self.GetFileURLForDataPath( 23 'frame_dom_access', 'frame_dom_access.html')) 24 25 v = self.ExecuteJavascript('window.domAutomationController.send(' + 26 'document.getElementById("myinput").nodeName)') 27 self.assertEqual(v, 'INPUT') 28 29 def testGetDOMValue(self): 30 self.NavigateToURL(self.GetFileURLForDataPath( 31 'frame_dom_access', 'frame_dom_access.html')) 32 33 v = self.GetDOMValue('document.getElementById("myinput").nodeName') 34 self.assertEqual(v, 'INPUT') 35 36 def testExecuteJavascriptInExtension(self): 37 """Test we can inject JavaScript into an extension.""" 38 dir_path = os.path.abspath( 39 os.path.join(self.DataDir(), 'extensions', 'js_injection_background')) 40 ext_id = self.InstallExtension(dir_path) 41 42 # Verify extension is enabled. 43 extension = self._GetExtensionInfoById(self.GetExtensionsInfo(), ext_id) 44 self.assertTrue(extension['is_enabled'], 45 msg='Extension was disabled by default') 46 47 # Get the background page's view. 48 background_view = self.WaitUntilExtensionViewLoaded( 49 view_type='EXTENSION_BACKGROUND_PAGE') 50 self.assertTrue(background_view, 51 msg='problematic background view: views = %s.' % 52 self.GetBrowserInfo()['extension_views']) 53 54 # Get values from background page's DOM 55 v = self.ExecuteJavascriptInRenderView( 56 'window.domAutomationController.send(' 57 'document.getElementById("myinput").nodeName)', background_view) 58 self.assertEqual(v, 'INPUT', 59 msg='Incorrect value returned (v = %s).' % v) 60 v = self.ExecuteJavascriptInRenderView( 61 'window.domAutomationController.send(bool_var)', background_view) 62 self.assertEqual(v, True, msg='Incorrect value returned (v = %s).' % v) 63 v = self.ExecuteJavascriptInRenderView( 64 'window.domAutomationController.send(int_var)', background_view) 65 self.assertEqual(v, 42, msg='Incorrect value returned (v = %s).' % v) 66 v = self.ExecuteJavascriptInRenderView( 67 'window.domAutomationController.send(str_var)', background_view) 68 self.assertEqual(v, 'foo', msg='Incorrect value returned (v = %s).' % v) 69 70 71if __name__ == '__main__': 72 pyauto_functional.Main() 73