2 * Copyright (C) 2011 Google Inc. All rights reserved.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following disclaimer
12 * in the documentation and/or other materials provided with the
14 * * Neither the name of Google Inc. nor the names of its
15 * contributors may be used to endorse or promote products derived from
16 * this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 importScript("ExtensionRegistryStub.js");
33 importScript("ExtensionAPI.js");
34 importScript("ExtensionAuditCategory.js");
38 * @implements {WebInspector.ExtensionServerAPI}
40 WebInspector.ExtensionServer = function()
42 this._clientObjects = {};
44 this._subscribers = {};
45 this._subscriptionStartHandlers = {};
46 this._subscriptionStopHandlers = {};
47 this._extraHeaders = {};
49 this._lastRequestId = 0;
50 this._registeredExtensions = {};
51 this._status = new WebInspector.ExtensionStatus();
53 var commands = WebInspector.extensionAPI.Commands;
55 this._registerHandler(commands.AddAuditCategory, this._onAddAuditCategory.bind(this));
56 this._registerHandler(commands.AddAuditResult, this._onAddAuditResult.bind(this));
57 this._registerHandler(commands.AddConsoleMessage, this._onAddConsoleMessage.bind(this));
58 this._registerHandler(commands.AddRequestHeaders, this._onAddRequestHeaders.bind(this));
59 this._registerHandler(commands.ApplyStyleSheet, this._onApplyStyleSheet.bind(this));
60 this._registerHandler(commands.CreatePanel, this._onCreatePanel.bind(this));
61 this._registerHandler(commands.CreateSidebarPane, this._onCreateSidebarPane.bind(this));
62 this._registerHandler(commands.CreateStatusBarButton, this._onCreateStatusBarButton.bind(this));
63 this._registerHandler(commands.EvaluateOnInspectedPage, this._onEvaluateOnInspectedPage.bind(this));
64 this._registerHandler(commands.ForwardKeyboardEvent, this._onForwardKeyboardEvent.bind(this));
65 this._registerHandler(commands.GetHAR, this._onGetHAR.bind(this));
66 this._registerHandler(commands.GetConsoleMessages, this._onGetConsoleMessages.bind(this));
67 this._registerHandler(commands.GetPageResources, this._onGetPageResources.bind(this));
68 this._registerHandler(commands.GetRequestContent, this._onGetRequestContent.bind(this));
69 this._registerHandler(commands.GetResourceContent, this._onGetResourceContent.bind(this));
70 this._registerHandler(commands.Reload, this._onReload.bind(this));
71 this._registerHandler(commands.SetOpenResourceHandler, this._onSetOpenResourceHandler.bind(this));
72 this._registerHandler(commands.SetResourceContent, this._onSetResourceContent.bind(this));
73 this._registerHandler(commands.SetSidebarHeight, this._onSetSidebarHeight.bind(this));
74 this._registerHandler(commands.SetSidebarContent, this._onSetSidebarContent.bind(this));
75 this._registerHandler(commands.SetSidebarPage, this._onSetSidebarPage.bind(this));
76 this._registerHandler(commands.ShowPanel, this._onShowPanel.bind(this));
77 this._registerHandler(commands.StopAuditCategoryRun, this._onStopAuditCategoryRun.bind(this));
78 this._registerHandler(commands.Subscribe, this._onSubscribe.bind(this));
79 this._registerHandler(commands.OpenResource, this._onOpenResource.bind(this));
80 this._registerHandler(commands.Unsubscribe, this._onUnsubscribe.bind(this));
81 this._registerHandler(commands.UpdateButton, this._onUpdateButton.bind(this));
82 this._registerHandler(commands.UpdateAuditProgress, this._onUpdateAuditProgress.bind(this));
83 window.addEventListener("message", this._onWindowMessage.bind(this), false);
85 this._initExtensions();
88 WebInspector.ExtensionServer.prototype = {
92 hasExtensions: function()
94 return !!Object.keys(this._registeredExtensions).length;
97 notifySearchAction: function(panelId, action, searchString)
99 this._postNotification(WebInspector.extensionAPI.Events.PanelSearch + panelId, action, searchString);
102 notifyViewShown: function(identifier, frameIndex)
104 this._postNotification(WebInspector.extensionAPI.Events.ViewShown + identifier, frameIndex);
107 notifyViewHidden: function(identifier)
109 this._postNotification(WebInspector.extensionAPI.Events.ViewHidden + identifier);
112 notifyButtonClicked: function(identifier)
114 this._postNotification(WebInspector.extensionAPI.Events.ButtonClicked + identifier);
117 _inspectedURLChanged: function(event)
120 var url = event.data;
121 this._postNotification(WebInspector.extensionAPI.Events.InspectedURLChanged, url);
124 startAuditRun: function(category, auditRun)
126 this._clientObjects[auditRun.id] = auditRun;
127 this._postNotification("audit-started-" + category.id, auditRun.id);
130 stopAuditRun: function(auditRun)
132 delete this._clientObjects[auditRun.id];
136 * @param {string} type
139 hasSubscribers: function(type)
141 return !!this._subscribers[type];
145 * @param {string} type
146 * @param {...*} vararg
148 _postNotification: function(type, vararg)
150 var subscribers = this._subscribers[type];
154 command: "notify-" + type,
155 arguments: Array.prototype.slice.call(arguments, 1)
157 for (var i = 0; i < subscribers.length; ++i)
158 subscribers[i].postMessage(message);
161 _onSubscribe: function(message, port)
163 var subscribers = this._subscribers[message.type];
165 subscribers.push(port);
167 this._subscribers[message.type] = [ port ];
168 if (this._subscriptionStartHandlers[message.type])
169 this._subscriptionStartHandlers[message.type]();
173 _onUnsubscribe: function(message, port)
175 var subscribers = this._subscribers[message.type];
178 subscribers.remove(port);
179 if (!subscribers.length) {
180 delete this._subscribers[message.type];
181 if (this._subscriptionStopHandlers[message.type])
182 this._subscriptionStopHandlers[message.type]();
186 _onAddRequestHeaders: function(message)
188 var id = message.extensionId;
189 if (typeof id !== "string")
190 return this._status.E_BADARGTYPE("extensionId", typeof id, "string");
191 var extensionHeaders = this._extraHeaders[id];
192 if (!extensionHeaders) {
193 extensionHeaders = {};
194 this._extraHeaders[id] = extensionHeaders;
196 for (var name in message.headers)
197 extensionHeaders[name] = message.headers[name];
198 var allHeaders = /** @type {!NetworkAgent.Headers} */ ({});
199 for (var extension in this._extraHeaders) {
200 var headers = this._extraHeaders[extension];
201 for (name in headers) {
202 if (typeof headers[name] === "string")
203 allHeaders[name] = headers[name];
206 NetworkAgent.setExtraHTTPHeaders(allHeaders);
209 _onApplyStyleSheet: function(message)
211 if (!WebInspector.experimentsSettings.applyCustomStylesheet.isEnabled())
213 var styleSheet = document.createElement("style");
214 styleSheet.textContent = message.styleSheet;
215 document.head.appendChild(styleSheet);
218 _onCreatePanel: function(message, port)
221 // The ids are generated on the client API side and must be unique, so the check below
222 // shouldn't be hit unless someone is bypassing the API.
223 if (id in this._clientObjects || id in WebInspector.panels)
224 return this._status.E_EXISTS(id);
226 var page = this._expandResourcePath(port._extensionOrigin, message.page);
227 var panelDescriptor = new WebInspector.ExtensionServerPanelDescriptor(id, message.title, new WebInspector.ExtensionPanel(id, page));
228 this._clientObjects[id] = panelDescriptor.panel();
229 WebInspector.inspectorView.addPanel(panelDescriptor);
230 return this._status.OK();
233 _onShowPanel: function(message)
235 // Note: WebInspector.showPanel already sanitizes input.
236 WebInspector.showPanel(message.id);
239 _onCreateStatusBarButton: function(message, port)
241 var panel = this._clientObjects[message.panel];
242 if (!panel || !(panel instanceof WebInspector.ExtensionPanel))
243 return this._status.E_NOTFOUND(message.panel);
244 var button = new WebInspector.ExtensionButton(message.id, this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled);
245 this._clientObjects[message.id] = button;
246 panel.addStatusBarItem(button.element);
247 return this._status.OK();
250 _onUpdateButton: function(message, port)
252 var button = this._clientObjects[message.id];
253 if (!button || !(button instanceof WebInspector.ExtensionButton))
254 return this._status.E_NOTFOUND(message.id);
255 button.update(this._expandResourcePath(port._extensionOrigin, message.icon), message.tooltip, message.disabled);
256 return this._status.OK();
259 _onCreateSidebarPane: function(message)
261 var panel = WebInspector.panel(message.panel);
263 return this._status.E_NOTFOUND(message.panel);
264 if (!panel.addExtensionSidebarPane)
265 return this._status.E_NOTSUPPORTED();
267 var sidebar = new WebInspector.ExtensionSidebarPane(message.title, id);
268 this._clientObjects[id] = sidebar;
269 panel.addExtensionSidebarPane(id, sidebar);
271 return this._status.OK();
274 _onSetSidebarHeight: function(message)
276 var sidebar = this._clientObjects[message.id];
278 return this._status.E_NOTFOUND(message.id);
279 sidebar.setHeight(message.height);
280 return this._status.OK();
283 _onSetSidebarContent: function(message, port)
285 var sidebar = this._clientObjects[message.id];
287 return this._status.E_NOTFOUND(message.id);
290 * @this {WebInspector.ExtensionServer}
292 function callback(error)
294 var result = error ? this._status.E_FAILED(error) : this._status.OK();
295 this._dispatchCallback(message.requestId, port, result);
297 if (message.evaluateOnPage)
298 return sidebar.setExpression(message.expression, message.rootTitle, message.evaluateOptions, port._extensionOrigin, callback.bind(this));
299 sidebar.setObject(message.expression, message.rootTitle, callback.bind(this));
302 _onSetSidebarPage: function(message, port)
304 var sidebar = this._clientObjects[message.id];
306 return this._status.E_NOTFOUND(message.id);
307 sidebar.setPage(this._expandResourcePath(port._extensionOrigin, message.page));
310 _onOpenResource: function(message)
312 var uiSourceCode = WebInspector.workspace.uiSourceCodeForURL(message.url);
314 WebInspector.Revealer.reveal(new WebInspector.UILocation(uiSourceCode, message.lineNumber, 0));
315 return this._status.OK();
318 var resource = WebInspector.resourceForURL(message.url);
320 WebInspector.Revealer.reveal(resource, message.lineNumber);
321 return this._status.OK();
324 var request = WebInspector.networkLog.requestForURL(message.url);
326 WebInspector.Revealer.reveal(request);
327 return this._status.OK();
330 return this._status.E_NOTFOUND(message.url);
333 _onSetOpenResourceHandler: function(message, port)
335 var name = this._registeredExtensions[port._extensionOrigin].name || ("Extension " + port._extensionOrigin);
336 if (message.handlerPresent)
337 WebInspector.openAnchorLocationRegistry.registerHandler(name, this._handleOpenURL.bind(this, port));
339 WebInspector.openAnchorLocationRegistry.unregisterHandler(name);
342 _handleOpenURL: function(port, details)
344 var url = /** @type {string} */ (details.url);
345 var contentProvider = WebInspector.workspace.uiSourceCodeForOriginURL(url) || WebInspector.resourceForURL(url);
346 if (!contentProvider)
349 var lineNumber = details.lineNumber;
350 if (typeof lineNumber === "number")
353 command: "open-resource",
354 resource: this._makeResource(contentProvider),
355 lineNumber: lineNumber
360 _onReload: function(message)
362 var options = /** @type {!ExtensionReloadOptions} */ (message.options || {});
363 NetworkAgent.setUserAgentOverride(typeof options.userAgent === "string" ? options.userAgent : "");
365 if (options.injectedScript)
366 injectedScript = "(function(){" + options.injectedScript + "})()";
367 var preprocessingScript = options.preprocessingScript;
368 WebInspector.resourceTreeModel.reloadPage(!!options.ignoreCache, injectedScript, preprocessingScript);
369 return this._status.OK();
372 _onEvaluateOnInspectedPage: function(message, port)
375 * @param {?Protocol.Error} error
376 * @param {?RuntimeAgent.RemoteObject} resultPayload
377 * @param {boolean=} wasThrown
378 * @this {WebInspector.ExtensionServer}
380 function callback(error, resultPayload, wasThrown)
383 if (error || !resultPayload)
384 result = this._status.E_PROTOCOLERROR(error.toString());
386 result = { isException: true, value: resultPayload.description };
388 result = { value: resultPayload.value };
390 this._dispatchCallback(message.requestId, port, result);
392 return this.evaluate(message.expression, true, true, message.evaluateOptions, port._extensionOrigin, callback.bind(this));
395 _onGetConsoleMessages: function()
397 return WebInspector.console.messages.map(this._makeConsoleMessage);
400 _onAddConsoleMessage: function(message)
402 function convertSeverity(level)
405 case WebInspector.extensionAPI.console.Severity.Log:
406 return WebInspector.ConsoleMessage.MessageLevel.Log;
407 case WebInspector.extensionAPI.console.Severity.Warning:
408 return WebInspector.ConsoleMessage.MessageLevel.Warning;
409 case WebInspector.extensionAPI.console.Severity.Error:
410 return WebInspector.ConsoleMessage.MessageLevel.Error;
411 case WebInspector.extensionAPI.console.Severity.Debug:
412 return WebInspector.ConsoleMessage.MessageLevel.Debug;
415 var level = convertSeverity(message.severity);
417 return this._status.E_BADARG("message.severity", message.severity);
419 var consoleMessage = WebInspector.ConsoleMessage.create(
420 WebInspector.ConsoleMessage.MessageSource.JS,
423 WebInspector.ConsoleMessage.MessageType.Log,
426 WebInspector.console.addMessage(consoleMessage);
429 _makeConsoleMessage: function(message)
431 function convertLevel(level)
436 case WebInspector.ConsoleMessage.MessageLevel.Log:
437 return WebInspector.extensionAPI.console.Severity.Log;
438 case WebInspector.ConsoleMessage.MessageLevel.Warning:
439 return WebInspector.extensionAPI.console.Severity.Warning;
440 case WebInspector.ConsoleMessage.MessageLevel.Error:
441 return WebInspector.extensionAPI.console.Severity.Error;
442 case WebInspector.ConsoleMessage.MessageLevel.Debug:
443 return WebInspector.extensionAPI.console.Severity.Debug;
445 return WebInspector.extensionAPI.console.Severity.Log;
449 severity: convertLevel(message.level),
453 result.url = message.url;
455 result.line = message.line;
459 _onGetHAR: function()
461 var requests = WebInspector.networkLog.requests;
462 var harLog = (new WebInspector.HARLog(requests)).build();
463 for (var i = 0; i < harLog.entries.length; ++i)
464 harLog.entries[i]._requestId = this._requestId(requests[i]);
469 * @param {!WebInspector.ContentProvider} contentProvider
471 _makeResource: function(contentProvider)
474 url: contentProvider.contentURL(),
475 type: contentProvider.contentType().name()
480 * @return {!Array.<!WebInspector.ContentProvider>}
482 _onGetPageResources: function()
487 * @this {WebInspector.ExtensionServer}
489 function pushResourceData(contentProvider)
491 if (!resources[contentProvider.contentURL()])
492 resources[contentProvider.contentURL()] = this._makeResource(contentProvider);
494 var uiSourceCodes = WebInspector.workspace.uiSourceCodesForProjectType(WebInspector.projectTypes.Network);
495 uiSourceCodes.forEach(pushResourceData.bind(this));
496 WebInspector.resourceTreeModel.forAllResources(pushResourceData.bind(this));
497 return Object.values(resources);
501 * @param {!WebInspector.ContentProvider} contentProvider
503 _getResourceContent: function(contentProvider, message, port)
506 * @param {?string} content
507 * @this {WebInspector.ExtensionServer}
509 function onContentAvailable(content)
512 encoding: (content === null) || contentProvider.contentType().isTextType() ? "" : "base64",
515 this._dispatchCallback(message.requestId, port, response);
518 contentProvider.requestContent(onContentAvailable.bind(this));
521 _onGetRequestContent: function(message, port)
523 var request = this._requestById(message.id);
525 return this._status.E_NOTFOUND(message.id);
526 this._getResourceContent(request, message, port);
529 _onGetResourceContent: function(message, port)
531 var url = /** @type {string} */ (message.url);
532 var contentProvider = WebInspector.workspace.uiSourceCodeForOriginURL(url) || WebInspector.resourceForURL(url);
533 if (!contentProvider)
534 return this._status.E_NOTFOUND(url);
535 this._getResourceContent(contentProvider, message, port);
538 _onSetResourceContent: function(message, port)
541 * @param {?Protocol.Error} error
542 * @this {WebInspector.ExtensionServer}
544 function callbackWrapper(error)
546 var response = error ? this._status.E_FAILED(error) : this._status.OK();
547 this._dispatchCallback(message.requestId, port, response);
550 var url = /** @type {string} */ (message.url);
551 var uiSourceCode = WebInspector.workspace.uiSourceCodeForOriginURL(url);
553 var resource = WebInspector.resourceTreeModel.resourceForURL(url);
555 return this._status.E_NOTFOUND(url);
556 return this._status.E_NOTSUPPORTED("Resource is not editable")
558 uiSourceCode.setWorkingCopy(message.content);
560 uiSourceCode.commitWorkingCopy(callbackWrapper.bind(this));
562 callbackWrapper.call(this, null);
565 _requestId: function(request)
567 if (!request._extensionRequestId) {
568 request._extensionRequestId = ++this._lastRequestId;
569 this._requests[request._extensionRequestId] = request;
571 return request._extensionRequestId;
574 _requestById: function(id)
576 return this._requests[id];
579 _onAddAuditCategory: function(message, port)
581 var category = new WebInspector.ExtensionAuditCategory(port._extensionOrigin, message.id, message.displayName, message.resultCount);
582 if (WebInspector.panel("audits").getCategory(category.id))
583 return this._status.E_EXISTS(category.id);
584 this._clientObjects[message.id] = category;
585 // FIXME: register module manager extension instead of waking up audits module.
586 WebInspector.panel("audits").addCategory(category);
589 _onAddAuditResult: function(message)
591 var auditResult = this._clientObjects[message.resultId];
593 return this._status.E_NOTFOUND(message.resultId);
595 auditResult.addResult(message.displayName, message.description, message.severity, message.details);
599 return this._status.OK();
602 _onUpdateAuditProgress: function(message)
604 var auditResult = this._clientObjects[message.resultId];
606 return this._status.E_NOTFOUND(message.resultId);
607 auditResult.updateProgress(Math.min(Math.max(0, message.progress), 1));
610 _onStopAuditCategoryRun: function(message)
612 var auditRun = this._clientObjects[message.resultId];
614 return this._status.E_NOTFOUND(message.resultId);
618 _onForwardKeyboardEvent: function(message)
620 const Esc = "U+001B";
622 if (!message.ctrlKey && !message.altKey && !message.metaKey && !/^F\d+$/.test(message.keyIdentifier) && message.keyIdentifier !== Esc)
624 // Fool around closure compiler -- it has its own notion of both KeyboardEvent constructor
625 // and initKeyboardEvent methods and overriding these in externs.js does not have effect.
626 var event = new window.KeyboardEvent(message.eventType, {
627 keyIdentifier: message.keyIdentifier,
628 location: message.location,
629 ctrlKey: message.ctrlKey,
630 altKey: message.altKey,
631 shiftKey: message.shiftKey,
632 metaKey: message.metaKey
634 document.dispatchEvent(event);
637 _dispatchCallback: function(requestId, port, result)
640 port.postMessage({ command: "callback", requestId: requestId, result: result });
643 _initExtensions: function()
645 this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ConsoleMessageAdded,
646 WebInspector.console, WebInspector.ConsoleModel.Events.MessageAdded, this._notifyConsoleMessageAdded);
647 this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.NetworkRequestFinished,
648 WebInspector.networkManager, WebInspector.NetworkManager.EventTypes.RequestFinished, this._notifyRequestFinished);
649 this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.ResourceAdded,
650 WebInspector.workspace,
651 WebInspector.Workspace.Events.UISourceCodeAdded,
652 this._notifyResourceAdded);
655 * @this {WebInspector.ExtensionServer}
657 function onElementsSubscriptionStarted()
659 WebInspector.notifications.addEventListener(WebInspector.NotificationService.Events.SelectedNodeChanged, this._notifyElementsSelectionChanged, this);
663 * @this {WebInspector.ExtensionServer}
665 function onElementsSubscriptionStopped()
667 WebInspector.notifications.removeEventListener(WebInspector.NotificationService.Events.SelectedNodeChanged, this._notifyElementsSelectionChanged, this);
670 this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.PanelObjectSelected + "elements",
671 onElementsSubscriptionStarted.bind(this), onElementsSubscriptionStopped.bind(this));
673 this._registerAutosubscriptionHandler(WebInspector.extensionAPI.Events.PanelObjectSelected + "sources",
674 WebInspector.notifications,
675 WebInspector.SourceFrame.Events.SelectionChanged,
676 this._notifySourceFrameSelectionChanged);
677 this._registerResourceContentCommittedHandler(this._notifyUISourceCodeContentCommitted);
680 * @this {WebInspector.ExtensionServer}
682 function onTimelineSubscriptionStarted()
684 WebInspector.timelineManager.addEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded,
685 this._notifyTimelineEventRecorded, this);
686 WebInspector.timelineManager.start();
690 * @this {WebInspector.ExtensionServer}
692 function onTimelineSubscriptionStopped()
694 WebInspector.timelineManager.stop();
695 WebInspector.timelineManager.removeEventListener(WebInspector.TimelineManager.EventTypes.TimelineEventRecorded,
696 this._notifyTimelineEventRecorded, this);
699 this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.TimelineEventRecorded,
700 onTimelineSubscriptionStarted.bind(this), onTimelineSubscriptionStopped.bind(this));
702 WebInspector.resourceTreeModel.addEventListener(WebInspector.ResourceTreeModel.EventTypes.InspectedURLChanged,
703 this._inspectedURLChanged, this);
705 InspectorExtensionRegistry.getExtensionsAsync();
709 * @param {!WebInspector.TextRange} textRange
711 _makeSourceSelection: function(textRange)
713 var sourcesPanel = WebInspector.inspectorView.panel("sources");
715 startLine: textRange.startLine,
716 startColumn: textRange.startColumn,
717 endLine: textRange.endLine,
718 endColumn: textRange.endColumn,
719 url: sourcesPanel.tabbedEditorContainer.currentFile().uri()
725 _notifySourceFrameSelectionChanged: function(event)
727 this._postNotification(WebInspector.extensionAPI.Events.PanelObjectSelected + "sources", this._makeSourceSelection(event.data));
730 _notifyConsoleMessageAdded: function(event)
732 this._postNotification(WebInspector.extensionAPI.Events.ConsoleMessageAdded, this._makeConsoleMessage(event.data));
735 _notifyResourceAdded: function(event)
737 var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data);
738 this._postNotification(WebInspector.extensionAPI.Events.ResourceAdded, this._makeResource(uiSourceCode));
741 _notifyUISourceCodeContentCommitted: function(event)
743 var uiSourceCode = /** @type {!WebInspector.UISourceCode} */ (event.data.uiSourceCode);
744 var content = /** @type {string} */ (event.data.content);
745 this._postNotification(WebInspector.extensionAPI.Events.ResourceContentCommitted, this._makeResource(uiSourceCode), content);
748 _notifyRequestFinished: function(event)
750 var request = /** @type {!WebInspector.NetworkRequest} */ (event.data);
751 this._postNotification(WebInspector.extensionAPI.Events.NetworkRequestFinished, this._requestId(request), (new WebInspector.HAREntry(request)).build());
754 _notifyElementsSelectionChanged: function()
756 this._postNotification(WebInspector.extensionAPI.Events.PanelObjectSelected + "elements");
759 _notifyTimelineEventRecorded: function(event)
761 this._postNotification(WebInspector.extensionAPI.Events.TimelineEventRecorded, event.data);
765 * @param {!Array.<!ExtensionDescriptor>} extensionInfos
767 addExtensions: function(extensionInfos)
769 extensionInfos.forEach(this._addExtension, this);
773 * @param {!ExtensionDescriptor} extensionInfo
775 _addExtension: function(extensionInfo)
777 const urlOriginRegExp = new RegExp("([^:]+:\/\/[^/]*)\/"); // Can't use regexp literal here, MinJS chokes on it.
778 var startPage = extensionInfo.startPage;
779 var name = extensionInfo.name;
782 var originMatch = urlOriginRegExp.exec(startPage);
784 console.error("Skipping extension with invalid URL: " + startPage);
787 var extensionOrigin = originMatch[1];
788 if (!this._registeredExtensions[extensionOrigin]) {
789 // See ExtensionAPI.js for details.
790 InspectorFrontendHost.setInjectedScriptForOrigin(extensionOrigin, buildExtensionAPIInjectedScript(extensionInfo));
791 this._registeredExtensions[extensionOrigin] = { name: name };
793 var iframe = document.createElement("iframe");
794 iframe.src = startPage;
795 iframe.style.display = "none";
796 document.body.appendChild(iframe);
798 console.error("Failed to initialize extension " + startPage + ":" + e);
804 _registerExtension: function(origin, port)
806 if (!this._registeredExtensions.hasOwnProperty(origin)) {
807 if (origin !== window.location.origin) // Just ignore inspector frames.
808 console.error("Ignoring unauthorized client request from " + origin);
811 port._extensionOrigin = origin;
812 port.addEventListener("message", this._onmessage.bind(this), false);
816 _onWindowMessage: function(event)
818 if (event.data === "registerExtension")
819 this._registerExtension(event.origin, event.ports[0]);
822 _onmessage: function(event)
824 var message = event.data;
827 if (message.command in this._handlers)
828 result = this._handlers[message.command](message, event.target);
830 result = this._status.E_NOTSUPPORTED(message.command);
832 if (result && message.requestId)
833 this._dispatchCallback(message.requestId, event.target, result);
836 _registerHandler: function(command, callback)
838 console.assert(command);
839 this._handlers[command] = callback;
842 _registerSubscriptionHandler: function(eventTopic, onSubscribeFirst, onUnsubscribeLast)
844 this._subscriptionStartHandlers[eventTopic] = onSubscribeFirst;
845 this._subscriptionStopHandlers[eventTopic] = onUnsubscribeLast;
848 _registerAutosubscriptionHandler: function(eventTopic, eventTarget, frontendEventType, handler)
850 this._registerSubscriptionHandler(eventTopic,
851 eventTarget.addEventListener.bind(eventTarget, frontendEventType, handler, this),
852 eventTarget.removeEventListener.bind(eventTarget, frontendEventType, handler, this));
855 _registerResourceContentCommittedHandler: function(handler)
858 * @this {WebInspector.ExtensionServer}
860 function addFirstEventListener()
862 WebInspector.workspace.addEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, handler, this);
863 WebInspector.workspace.setHasResourceContentTrackingExtensions(true);
867 * @this {WebInspector.ExtensionServer}
869 function removeLastEventListener()
871 WebInspector.workspace.setHasResourceContentTrackingExtensions(false);
872 WebInspector.workspace.removeEventListener(WebInspector.Workspace.Events.UISourceCodeContentCommitted, handler, this);
875 this._registerSubscriptionHandler(WebInspector.extensionAPI.Events.ResourceContentCommitted,
876 addFirstEventListener.bind(this),
877 removeLastEventListener.bind(this));
880 _expandResourcePath: function(extensionPath, resourcePath)
884 return extensionPath + this._normalizePath(resourcePath);
887 _normalizePath: function(path)
889 var source = path.split("/");
892 for (var i = 0; i < source.length; ++i) {
893 if (source[i] === ".")
895 // Ignore empty path components resulting from //, as well as a leading and traling slashes.
896 if (source[i] === "")
898 if (source[i] === "..")
901 result.push(source[i]);
903 return "/" + result.join("/");
907 * @param {string} expression
908 * @param {boolean} exposeCommandLineAPI
909 * @param {boolean} returnByValue
910 * @param {?Object} options
911 * @param {string} securityOrigin
912 * @param {function(?string, !RuntimeAgent.RemoteObject, boolean=)} callback
913 * @return {!WebInspector.ExtensionStatus.Record|undefined}
915 evaluate: function(expression, exposeCommandLineAPI, returnByValue, options, securityOrigin, callback)
920 * @param {string} url
923 function resolveURLToFrame(url)
926 function hasMatchingURL(frame)
928 found = (frame.url === url) ? frame : null;
931 WebInspector.resourceTreeModel.frames().some(hasMatchingURL);
935 if (typeof options === "object") {
936 var frame = options.frameURL ? resolveURLToFrame(options.frameURL) : WebInspector.resourceTreeModel.mainFrame;
938 if (options.frameURL)
939 console.warn("evaluate: there is no frame with URL " + options.frameURL);
941 console.warn("evaluate: the main frame is not yet available");
942 return this._status.E_NOTFOUND(options.frameURL || "<top>");
945 var contextSecurityOrigin;
946 if (options.useContentScriptContext)
947 contextSecurityOrigin = securityOrigin;
948 else if (options.scriptExecutionContext)
949 contextSecurityOrigin = options.scriptExecutionContext;
951 var frameContextList = WebInspector.runtimeModel.contextListByFrame(frame);
953 if (contextSecurityOrigin) {
954 context = frameContextList.contextBySecurityOrigin(contextSecurityOrigin);
956 console.warn("The JavaScript context " + contextSecurityOrigin + " was not found in the frame " + frame.url)
957 return this._status.E_NOTFOUND(contextSecurityOrigin)
960 context = frameContextList.mainWorldContext();
962 return this._status.E_FAILED(frame.url + " has no execution context");
965 contextId = context.id;
967 RuntimeAgent.evaluate(expression, "extension", exposeCommandLineAPI, true, contextId, returnByValue, false, callback);
973 * @param {string} name
974 * @param {string} title
975 * @param {!WebInspector.Panel} panel
976 * @implements {WebInspector.PanelDescriptor}
978 WebInspector.ExtensionServerPanelDescriptor = function(name, title, panel)
985 WebInspector.ExtensionServerPanelDescriptor.prototype = {
1003 * @return {!WebInspector.Panel}
1014 WebInspector.ExtensionStatus = function()
1017 * @param {string} code
1018 * @param {string} description
1019 * @return {!WebInspector.ExtensionStatus.Record}
1021 function makeStatus(code, description)
1023 var details = Array.prototype.slice.call(arguments, 2);
1024 var status = { code: code, description: description, details: details };
1025 if (code !== "OK") {
1026 status.isError = true;
1027 console.log("Extension server error: " + String.vsprintf(description, details));
1032 this.OK = makeStatus.bind(null, "OK", "OK");
1033 this.E_EXISTS = makeStatus.bind(null, "E_EXISTS", "Object already exists: %s");
1034 this.E_BADARG = makeStatus.bind(null, "E_BADARG", "Invalid argument %s: %s");
1035 this.E_BADARGTYPE = makeStatus.bind(null, "E_BADARGTYPE", "Invalid type for argument %s: got %s, expected %s");
1036 this.E_NOTFOUND = makeStatus.bind(null, "E_NOTFOUND", "Object not found: %s");
1037 this.E_NOTSUPPORTED = makeStatus.bind(null, "E_NOTSUPPORTED", "Object does not support requested operation: %s");
1038 this.E_PROTOCOLERROR = makeStatus.bind(null, "E_PROTOCOLERROR", "Inspector protocol error: %s");
1039 this.E_FAILED = makeStatus.bind(null, "E_FAILED", "Operation failed: %s");
1043 * @typedef {{code: string, description: string, details: !Array.<*>}}
1045 WebInspector.ExtensionStatus.Record;
1047 WebInspector.extensionAPI = {};
1048 defineCommonExtensionSymbols(WebInspector.extensionAPI);
1050 importScript("ExtensionPanel.js");
1051 importScript("ExtensionView.js");