Tag Archives: Chrome

Kyiv GTUG HTML5 hackathon #chromekyiv.

Last saturday (23.10.10) I was a participant of the HTML5 hackathon day organized by Kyiv GTUG can be followed in twitter #chromekyiv . There were a lot of fun.

Excellent speech by Michael Mahemoff @mahemoff about HTML5 features and perfect talks at coffee-breaks and lunch. I’ve got a lot of good impressions and spent my day with a big pleasure.

After Michael’s speech we had a lunch, during that we (@yasik and @shooshpanchick and me aka @webdizz) were involved in discussions regarding different aspects of developer’s life and technologies and generating ideas for our demos.

From the beginning of idea generating period of the day we decided to build up an app that will show tweets on the Earth rotating with appropriate speed  from twitter . But after several attempts to get a developer key we’ve got stocked. dev.twitter.com was down:(. It was a really shame.

Then we decided to move to something another and again was in a stock.

And time gone on…

So at last we found out an idea to work with. We decided to build an extension for Google Chrome to grab addresses from current page and display those addresses on the Google Maps or on the Yandex Maps and dived in coding.

Our extension contains HTML5 elements tag “nav” in the menu to choose map to display found addresses on and tag “canvas” circles to highlight found and not found addresses on the Google Maps. Also there is a lot of JavaScript magic.

So, time again was against us and it blown out.

The time for demo begun. We were first to demonstrate our work and seems it was ok according to results.

There are following results, we took first place as a team and one girl between all participants Anna Shaban with CSS3 photo gallery and hard-to-describe visual effect involving your name being shown at a million angles and opacities.

All winners were awarded with great presents and invitation to GDD 2010 in Moscow.

I’d like to thank to people who organized such a great event from Kyiv GTUG and to Michael Mahemoff.

Medeniye loogat Google Chrome extension

Вот и настал этот долгожданный час:) Сегодня вышла первая версия расширения для Google Chrome.

Функциональность расширения заключается в обеспечении возможности поиска перевода для выбранного слова в словаре Medeniye loogat. Для поиска перевода необходимо нажать кнопку Ctrl и кликнуть 2 раза на интересующем слове для его выделения, затем отобразится найденный перевод либо похожие слова.

Описанный выше функционал пожалуй весь арсенал данного расширения, основной же особенностью является техническая сторона, а именно – оно написано полностью на GWT.

Расширение можно установить с этой страници: https://chrome.google.com/extensions/detail/kalnlennobeikiffcdhdnjpnmmbjdigi .

powermock – real power for testing untestable stuff

Last weekend was spent to make my Chrome extension base on GWT working with content scripts written using GWT. As one of main concept is to keep my trust for my code on appropriate level. To achieve this I’m practicing in TDD. For testing purposes I use JUnit 4.x and for mocking Mockito.

I’d like to spend some thime on MockitoMockito is really powerful mocking framework with sweat features, all ones you can find here http://code.google.com/p/mockito/wiki/FeaturesAndMotivations. As for me I really like nice and laconic syntax ans simplicity.

The information above is not a main reason of this post, the main one is to tell about my experience to test code using GWT classes e.g. finals and statics. After some time spent to google something will be helpful I’v found out PowerMock. This framework provides abilities to mock static classes and final methods and as you might know GWT uses a lot of such stuff.

For example I need to test method which handles browser page’ events from content script and pass related data to background page to process those data. The issue was to assign event for whole page, this is impossible as RootPanel.get() does not support event handlers. So I’ve found out another way – use Event.addNativePreviewHandler and NativePreviewHandler to hande events.

So I created implementation of NativePreviewHandler and started from test. Logic is quite simple but I was unable to use GWT code in my POJT (Plain Old Java Test), as NativeEvent returned by NativePreviewEvent as an argument for method NativePreviewHandler.onPreviewNativeEvent requires GWT.create method call, which in turn need a GWT context to be set up. But this is not what I want.  I’d like to have simple and fast tests without necessity to compile Java to JavaScript and only after to test.

In this situation I need mock GWT classes to be able to test my code, but Mockito does not support mocking for static classes and final methods. So PowerMock solved my trouble. Example of usage:

@PrepareOnlyThisForTest({ NativeEvent.class, SelectionProvider.class })
@SuppressStaticInitializationFor({ "com.google.gwt.dom.client.NativeEvent" })
public class ContentScriptEventHandlerTest {
	private ChromePort port;
        // Creates mock for class with final methods
	private NativeEvent event = PowerMockito.mock(NativeEvent.class);
	public void setUp() throws Exception {
                // Creates mock for static class
                // assign return value for method from static class
                // there was stackoverflow and we do not need to call for equals
		PowerMockito.suppress(event.getClass().getMethod("equals", Object.class));
                // assign return values for final methods
	public void shouldNotConsumeNotMouseupEvent() throws Exception {
		ContentScriptEventHandler eventHandler = new ContentScriptEventHandler(port);
		NativePreviewEvent previewEvent = mock(NativePreviewEvent.class);
		verify(previewEvent, never()).consume();

That’s it. Have enjoy testing…

Build extension for Google Chrome with GWT

From time-to-time I’m coming back to do some coding to provide Chrome Extension with helping to translate and remember words.

From this repository http://github.com/webdizz/clt now you can download the source code of the extension, however it is in the pre-pre-alpha state. But the main reason of this post is to tell about implemented abilities to write ContentScript using GWT.

Initial code of the GWT linker for Chrome Extension was pulled from SpeedTracer extension, after that I’ve provide some enhancements to support additional features.

  • GWT Linker for Chrome Extension was extracted into separate subproject;
  • ComponentGenerator was refactored and provided with initial pack of tests;
  • ExtensionScript artifact was added – which provides you abilities to define external JavaScript file to be injected into the BackgroundPage and loaded on extension initialization. This is useful for example when you are working with Google Language API or another required JavaScript library which you cannot include as a static content;
  • ContentScript now support all_frames attribute;
  • GwtContentScript artifact was introduced – which provides you abilities to implement ContentScript code with GWT and include it as a static ContentScript into your extension. Example of this you can find in my extension. But there is an issue – I’m not able to resolve path to extracted war to copy generated JavaScript file from GWTContentScript module into extension module, but there is workaround for this – you need to define own launcher (for Eclipse) to build extension. Example launcher can be downloaded here http://github.com/webdizz/clt/blob/master/clt-crx/Build-clt-extension.launch.

That’s it for now, have a nice week.

GWT based Chrome extension

Доброго времени суток, однако прошел уже месяц с хвостиком с момента моего последнего опуса, но дабы не допустить возникновения паутины в собственном блоге хочу поделиться повествованием об освоении написания расширения для браузера Chrome.

Как обычно знакомство с чем-то новым и неизведанным является очень интересным и занимательным занятием, помимо этого еще и с присутствием “challenges” . Ближе к делу…

Итак в этот раз я взялся за написание плагина для Chrome. Я не буду описывать архитектуру API для написания расширений, т.к. заинтересовавшийся разработчик сможе ознакомиться с ней тут. Вкратце – плагин представляет собой файл-декларация плагина – manifest.json, background-html страницу (содержит общую логику расширения) и подключаемые js-файлы. Написание плагина на чистом JavaScript не представляет собой огромного интереса, в отличии от использования для этого GWT.

Как оказалось официальной поддержки Chrome extensions в GWT нет, но погуглив я наткнулся на кое-какую информацию по эьлму вопросу. В релиз GWT 2.0 включается расширение для Chrome Speed Tracer, которое написано с использованием GWT. Заложенные возможности к гибкому расширению с помошью GWT linker позволяют применять этот замечательный фреймворк очень широко.  Сделав чекаут проекта Speed Tracer я начал вникать в способ написания расширения. Как оказалось линкер в Speed Tracer не поддерживает ряд появившихся в новом API Chrome методов и типов, так мною были дописаны возможность подключать скрипты в background page, пости-инициализация подключаемых скриптов и немного доработан линкер до нужд моего расширения.

Исходный код линкера  расширеним будет предоставлен немного позже, а пока перечислю некоторые проблемы, с которыми пришлось столкнуться мне.

  • коммуникация между страницами и скриптами раширения – временно решена использованием паттерна Singleton;
  • логика перехвата событий должна находиться в подключаемых скриптах, т.к. они исполняются в контексте загруженной страницы.

На этом пока все, продолжение следует…