1 // Copyright (c) 2011 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.
5 #include "chrome/renderer/search_extension.h"
10 #include "base/command_line.h"
11 #include "chrome/renderer/searchbox.h"
12 #include "content/public/renderer/render_view.h"
13 #include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
14 #include "v8/include/v8.h"
16 using WebKit::WebFrame
;
17 using WebKit::WebView
;
19 namespace extensions_v8
{
21 const char* const kSearchExtensionName
= "v8/InstantSearch";
23 class SearchExtensionWrapper
: public v8::Extension
{
25 SearchExtensionWrapper();
27 // Allows v8's javascript code to call the native functions defined
28 // in this class for window.chrome.
29 virtual v8::Handle
<v8::FunctionTemplate
> GetNativeFunction(
30 v8::Handle
<v8::String
> name
);
32 // Helper function to find the RenderView. May return NULL.
33 static content::RenderView
* GetRenderView();
35 // Implementation of window.chrome.setSuggestResult.
36 static v8::Handle
<v8::Value
> SetSuggestResult(const v8::Arguments
& args
);
39 DISALLOW_COPY_AND_ASSIGN(SearchExtensionWrapper
);
42 SearchExtensionWrapper::SearchExtensionWrapper()
43 : v8::Extension(kSearchExtensionName
,
47 "chrome.setSuggestResult = function(text) {"
48 " native function NativeSetSuggestResult();"
49 " NativeSetSuggestResult(text);"
53 v8::Handle
<v8::FunctionTemplate
> SearchExtensionWrapper::GetNativeFunction(
54 v8::Handle
<v8::String
> name
) {
55 if (name
->Equals(v8::String::New("NativeSetSuggestResult"))) {
56 return v8::FunctionTemplate::New(SetSuggestResult
);
59 return v8::Handle
<v8::FunctionTemplate
>();
63 content::RenderView
* SearchExtensionWrapper::GetRenderView() {
64 WebFrame
* webframe
= WebFrame::frameForEnteredContext();
65 DCHECK(webframe
) << "There should be an active frame since we just got "
66 "a native function called.";
67 if (!webframe
) return NULL
;
69 WebView
* webview
= webframe
->view();
70 if (!webview
) return NULL
; // can happen during closing
72 return content::RenderView::FromWebView(webview
);
76 v8::Handle
<v8::Value
> SearchExtensionWrapper::SetSuggestResult(
77 const v8::Arguments
& args
) {
78 if (!args
.Length() || !args
[0]->IsString()) return v8::Undefined();
80 content::RenderView
* render_view
= GetRenderView();
81 if (!render_view
) return v8::Undefined();
83 std::vector
<std::string
> suggestions
;
84 suggestions
.push_back(std::string(*v8::String::Utf8Value(args
[0])));
85 SearchBox::Get(render_view
)->SetSuggestions(suggestions
,
86 INSTANT_COMPLETE_NOW
);
87 return v8::Undefined();
90 v8::Extension
* SearchExtension::Get() {
91 return new SearchExtensionWrapper();
94 } // namespace extensions_v8