ExtensionAPI.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. /*
  2. * Copyright (C) 2012 Google Inc. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions are
  6. * met:
  7. *
  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
  13. * distribution.
  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.
  17. *
  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.
  29. */
  30. function defineCommonExtensionSymbols(apiPrivate)
  31. {
  32. if (!apiPrivate.audits)
  33. apiPrivate.audits = {};
  34. apiPrivate.audits.Severity = {
  35. Info: "info",
  36. Warning: "warning",
  37. Severe: "severe"
  38. };
  39. if (!apiPrivate.console)
  40. apiPrivate.console = {};
  41. apiPrivate.console.Severity = {
  42. Debug: "debug",
  43. Log: "log",
  44. Warning: "warning",
  45. Error: "error"
  46. };
  47. if (!apiPrivate.panels)
  48. apiPrivate.panels = {};
  49. apiPrivate.panels.SearchAction = {
  50. CancelSearch: "cancelSearch",
  51. PerformSearch: "performSearch",
  52. NextSearchResult: "nextSearchResult",
  53. PreviousSearchResult: "previousSearchResult"
  54. };
  55. apiPrivate.Events = {
  56. AuditStarted: "audit-started-",
  57. ButtonClicked: "button-clicked-",
  58. ConsoleMessageAdded: "console-message-added",
  59. ElementsPanelObjectSelected: "panel-objectSelected-elements",
  60. NetworkRequestFinished: "network-request-finished",
  61. OpenResource: "open-resource",
  62. PanelSearch: "panel-search-",
  63. Reload: "Reload",
  64. ResourceAdded: "resource-added",
  65. ResourceContentCommitted: "resource-content-committed",
  66. TimelineEventRecorded: "timeline-event-recorded",
  67. ViewShown: "view-shown-",
  68. ViewHidden: "view-hidden-"
  69. };
  70. apiPrivate.Commands = {
  71. AddAuditCategory: "addAuditCategory",
  72. AddAuditResult: "addAuditResult",
  73. AddConsoleMessage: "addConsoleMessage",
  74. AddRequestHeaders: "addRequestHeaders",
  75. CreatePanel: "createPanel",
  76. CreateSidebarPane: "createSidebarPane",
  77. CreateStatusBarButton: "createStatusBarButton",
  78. EvaluateOnInspectedPage: "evaluateOnInspectedPage",
  79. GetConsoleMessages: "getConsoleMessages",
  80. GetHAR: "getHAR",
  81. GetPageResources: "getPageResources",
  82. GetRequestContent: "getRequestContent",
  83. GetResourceContent: "getResourceContent",
  84. Subscribe: "subscribe",
  85. SetOpenResourceHandler: "setOpenResourceHandler",
  86. SetResourceContent: "setResourceContent",
  87. SetSidebarContent: "setSidebarContent",
  88. SetSidebarHeight: "setSidebarHeight",
  89. SetSidebarPage: "setSidebarPage",
  90. ShowPanel: "showPanel",
  91. StopAuditCategoryRun: "stopAuditCategoryRun",
  92. Unsubscribe: "unsubscribe",
  93. UpdateAuditProgress: "updateAuditProgress",
  94. UpdateButton: "updateButton",
  95. InspectedURLChanged: "inspectedURLChanged"
  96. };
  97. }
  98. function injectedExtensionAPI(injectedScriptId)
  99. {
  100. var apiPrivate = {};
  101. defineCommonExtensionSymbols(apiPrivate);
  102. var commands = apiPrivate.Commands;
  103. var events = apiPrivate.Events;
  104. var userAction = false;
  105. // Here and below, all constructors are private to API implementation.
  106. // For a public type Foo, if internal fields are present, these are on
  107. // a private FooImpl type, an instance of FooImpl is used in a closure
  108. // by Foo consutrctor to re-bind publicly exported members to an instance
  109. // of Foo.
  110. /**
  111. * @constructor
  112. */
  113. function EventSinkImpl(type, customDispatch)
  114. {
  115. this._type = type;
  116. this._listeners = [];
  117. this._customDispatch = customDispatch;
  118. }
  119. EventSinkImpl.prototype = {
  120. addListener: function(callback)
  121. {
  122. if (typeof callback !== "function")
  123. throw "addListener: callback is not a function";
  124. if (this._listeners.length === 0)
  125. extensionServer.sendRequest({ command: commands.Subscribe, type: this._type });
  126. this._listeners.push(callback);
  127. extensionServer.registerHandler("notify-" + this._type, this._dispatch.bind(this));
  128. },
  129. removeListener: function(callback)
  130. {
  131. var listeners = this._listeners;
  132. for (var i = 0; i < listeners.length; ++i) {
  133. if (listeners[i] === callback) {
  134. listeners.splice(i, 1);
  135. break;
  136. }
  137. }
  138. if (this._listeners.length === 0)
  139. extensionServer.sendRequest({ command: commands.Unsubscribe, type: this._type });
  140. },
  141. _fire: function()
  142. {
  143. var listeners = this._listeners.slice();
  144. for (var i = 0; i < listeners.length; ++i)
  145. listeners[i].apply(null, arguments);
  146. },
  147. _dispatch: function(request)
  148. {
  149. if (this._customDispatch)
  150. this._customDispatch.call(this, request);
  151. else
  152. this._fire.apply(this, request.arguments);
  153. }
  154. }
  155. /**
  156. * @constructor
  157. */
  158. function InspectorExtensionAPI()
  159. {
  160. this.audits = new Audits();
  161. this.inspectedWindow = new InspectedWindow();
  162. this.panels = new Panels();
  163. this.network = new Network();
  164. defineDeprecatedProperty(this, "webInspector", "resources", "network");
  165. this.timeline = new Timeline();
  166. this.console = new ConsoleAPI();
  167. }
  168. /**
  169. * @constructor
  170. */
  171. InspectorExtensionAPI.prototype = {
  172. log: function(message)
  173. {
  174. extensionServer.sendRequest({ command: commands.Log, message: message });
  175. }
  176. }
  177. /**
  178. * @constructor
  179. */
  180. function ConsoleAPI()
  181. {
  182. this.onMessageAdded = new EventSink(events.ConsoleMessageAdded);
  183. }
  184. ConsoleAPI.prototype = {
  185. getMessages: function(callback)
  186. {
  187. extensionServer.sendRequest({ command: commands.GetConsoleMessages }, callback);
  188. },
  189. addMessage: function(severity, text, url, line)
  190. {
  191. extensionServer.sendRequest({ command: commands.AddConsoleMessage, severity: severity, text: text, url: url, line: line });
  192. },
  193. get Severity()
  194. {
  195. return apiPrivate.console.Severity;
  196. }
  197. }
  198. /**
  199. * @constructor
  200. */
  201. function Network()
  202. {
  203. function dispatchRequestEvent(message)
  204. {
  205. var request = message.arguments[1];
  206. request.__proto__ = new Request(message.arguments[0]);
  207. this._fire(request);
  208. }
  209. this.onRequestFinished = new EventSink(events.NetworkRequestFinished, dispatchRequestEvent);
  210. defineDeprecatedProperty(this, "network", "onFinished", "onRequestFinished");
  211. this.onNavigated = new EventSink(events.InspectedURLChanged);
  212. }
  213. Network.prototype = {
  214. getHAR: function(callback)
  215. {
  216. function callbackWrapper(result)
  217. {
  218. var entries = (result && result.entries) || [];
  219. for (var i = 0; i < entries.length; ++i) {
  220. entries[i].__proto__ = new Request(entries[i]._requestId);
  221. delete entries[i]._requestId;
  222. }
  223. callback(result);
  224. }
  225. return extensionServer.sendRequest({ command: commands.GetHAR }, callback && callbackWrapper);
  226. },
  227. addRequestHeaders: function(headers)
  228. {
  229. return extensionServer.sendRequest({ command: commands.AddRequestHeaders, headers: headers, extensionId: window.location.hostname });
  230. }
  231. }
  232. /**
  233. * @constructor
  234. */
  235. function RequestImpl(id)
  236. {
  237. this._id = id;
  238. }
  239. RequestImpl.prototype = {
  240. getContent: function(callback)
  241. {
  242. function callbackWrapper(response)
  243. {
  244. callback(response.content, response.encoding);
  245. }
  246. extensionServer.sendRequest({ command: commands.GetRequestContent, id: this._id }, callback && callbackWrapper);
  247. }
  248. }
  249. /**
  250. * @constructor
  251. */
  252. function Panels()
  253. {
  254. var panels = {
  255. elements: new ElementsPanel()
  256. };
  257. function panelGetter(name)
  258. {
  259. return panels[name];
  260. }
  261. for (var panel in panels)
  262. this.__defineGetter__(panel, panelGetter.bind(null, panel));
  263. }
  264. Panels.prototype = {
  265. create: function(title, icon, page, callback)
  266. {
  267. var id = "extension-panel-" + extensionServer.nextObjectId();
  268. var request = {
  269. command: commands.CreatePanel,
  270. id: id,
  271. title: title,
  272. icon: icon,
  273. page: page
  274. };
  275. extensionServer.sendRequest(request, callback && callback.bind(this, new ExtensionPanel(id)));
  276. },
  277. setOpenResourceHandler: function(callback)
  278. {
  279. var hadHandler = extensionServer.hasHandler(events.OpenResource);
  280. if (!callback)
  281. extensionServer.unregisterHandler(events.OpenResource);
  282. else {
  283. function callbackWrapper(message)
  284. {
  285. // Allow the panel to show itself when handling the event.
  286. userAction = true;
  287. try {
  288. callback.call(null, new Resource(message.resource), message.lineNumber);
  289. } finally {
  290. userAction = false;
  291. }
  292. }
  293. extensionServer.registerHandler(events.OpenResource, callbackWrapper);
  294. }
  295. // Only send command if we either removed an existing handler or added handler and had none before.
  296. if (hadHandler === !callback)
  297. extensionServer.sendRequest({ command: commands.SetOpenResourceHandler, "handlerPresent": !!callback });
  298. },
  299. get SearchAction()
  300. {
  301. return apiPrivate.panels.SearchAction;
  302. }
  303. }
  304. /**
  305. * @constructor
  306. */
  307. function ExtensionViewImpl(id)
  308. {
  309. this._id = id;
  310. function dispatchShowEvent(message)
  311. {
  312. var frameIndex = message.arguments[0];
  313. this._fire(window.parent.frames[frameIndex]);
  314. }
  315. this.onShown = new EventSink(events.ViewShown + id, dispatchShowEvent);
  316. this.onHidden = new EventSink(events.ViewHidden + id);
  317. }
  318. /**
  319. * @constructor
  320. */
  321. function PanelWithSidebarImpl(id)
  322. {
  323. this._id = id;
  324. }
  325. PanelWithSidebarImpl.prototype = {
  326. createSidebarPane: function(title, callback)
  327. {
  328. var id = "extension-sidebar-" + extensionServer.nextObjectId();
  329. var request = {
  330. command: commands.CreateSidebarPane,
  331. panel: this._id,
  332. id: id,
  333. title: title
  334. };
  335. function callbackWrapper()
  336. {
  337. callback(new ExtensionSidebarPane(id));
  338. }
  339. extensionServer.sendRequest(request, callback && callbackWrapper);
  340. },
  341. __proto__: ExtensionViewImpl.prototype
  342. }
  343. /**
  344. * @constructor
  345. * @extends {PanelWithSidebar}
  346. */
  347. function ElementsPanel()
  348. {
  349. var id = "elements";
  350. PanelWithSidebar.call(this, id);
  351. this.onSelectionChanged = new EventSink(events.ElementsPanelObjectSelected);
  352. }
  353. /**
  354. * @constructor
  355. * @extends {ExtensionViewImpl}
  356. */
  357. function ExtensionPanelImpl(id)
  358. {
  359. ExtensionViewImpl.call(this, id);
  360. this.onSearch = new EventSink(events.PanelSearch + id);
  361. }
  362. ExtensionPanelImpl.prototype = {
  363. createStatusBarButton: function(iconPath, tooltipText, disabled)
  364. {
  365. var id = "button-" + extensionServer.nextObjectId();
  366. var request = {
  367. command: commands.CreateStatusBarButton,
  368. panel: this._id,
  369. id: id,
  370. icon: iconPath,
  371. tooltip: tooltipText,
  372. disabled: !!disabled
  373. };
  374. extensionServer.sendRequest(request);
  375. return new Button(id);
  376. },
  377. show: function()
  378. {
  379. if (!userAction)
  380. return;
  381. var request = {
  382. command: commands.ShowPanel,
  383. id: this._id
  384. };
  385. extensionServer.sendRequest(request);
  386. },
  387. __proto__: ExtensionViewImpl.prototype
  388. }
  389. /**
  390. * @constructor
  391. * @extends {ExtensionViewImpl}
  392. */
  393. function ExtensionSidebarPaneImpl(id)
  394. {
  395. ExtensionViewImpl.call(this, id);
  396. }
  397. ExtensionSidebarPaneImpl.prototype = {
  398. setHeight: function(height)
  399. {
  400. extensionServer.sendRequest({ command: commands.SetSidebarHeight, id: this._id, height: height });
  401. },
  402. setExpression: function(expression, rootTitle, evaluateOptions)
  403. {
  404. var request = {
  405. command: commands.SetSidebarContent,
  406. id: this._id,
  407. expression: expression,
  408. rootTitle: rootTitle,
  409. evaluateOnPage: true,
  410. };
  411. if (typeof evaluateOptions === "object")
  412. request.evaluateOptions = evaluateOptions;
  413. extensionServer.sendRequest(request, extractCallbackArgument(arguments));
  414. },
  415. setObject: function(jsonObject, rootTitle, callback)
  416. {
  417. extensionServer.sendRequest({ command: commands.SetSidebarContent, id: this._id, expression: jsonObject, rootTitle: rootTitle }, callback);
  418. },
  419. setPage: function(page)
  420. {
  421. extensionServer.sendRequest({ command: commands.SetSidebarPage, id: this._id, page: page });
  422. }
  423. }
  424. /**
  425. * @constructor
  426. */
  427. function ButtonImpl(id)
  428. {
  429. this._id = id;
  430. this.onClicked = new EventSink(events.ButtonClicked + id);
  431. }
  432. ButtonImpl.prototype = {
  433. update: function(iconPath, tooltipText, disabled)
  434. {
  435. var request = {
  436. command: commands.UpdateButton,
  437. id: this._id,
  438. icon: iconPath,
  439. tooltip: tooltipText,
  440. disabled: !!disabled
  441. };
  442. extensionServer.sendRequest(request);
  443. }
  444. };
  445. /**
  446. * @constructor
  447. */
  448. function Audits()
  449. {
  450. }
  451. Audits.prototype = {
  452. addCategory: function(displayName, resultCount)
  453. {
  454. var id = "extension-audit-category-" + extensionServer.nextObjectId();
  455. if (typeof resultCount !== "undefined")
  456. console.warn("Passing resultCount to audits.addCategory() is deprecated. Use AuditResult.updateProgress() instead.");
  457. extensionServer.sendRequest({ command: commands.AddAuditCategory, id: id, displayName: displayName, resultCount: resultCount });
  458. return new AuditCategory(id);
  459. }
  460. }
  461. /**
  462. * @constructor
  463. */
  464. function AuditCategoryImpl(id)
  465. {
  466. function dispatchAuditEvent(request)
  467. {
  468. var auditResult = new AuditResult(request.arguments[0]);
  469. try {
  470. this._fire(auditResult);
  471. } catch (e) {
  472. console.error("Uncaught exception in extension audit event handler: " + e);
  473. auditResult.done();
  474. }
  475. }
  476. this._id = id;
  477. this.onAuditStarted = new EventSink(events.AuditStarted + id, dispatchAuditEvent);
  478. }
  479. /**
  480. * @constructor
  481. */
  482. function AuditResultImpl(id)
  483. {
  484. this._id = id;
  485. this.createURL = this._nodeFactory.bind(null, "url");
  486. this.createSnippet = this._nodeFactory.bind(null, "snippet");
  487. this.createText = this._nodeFactory.bind(null, "text");
  488. this.createObject = this._nodeFactory.bind(null, "object");
  489. this.createNode = this._nodeFactory.bind(null, "node");
  490. }
  491. AuditResultImpl.prototype = {
  492. addResult: function(displayName, description, severity, details)
  493. {
  494. // shorthand for specifying details directly in addResult().
  495. if (details && !(details instanceof AuditResultNode))
  496. details = new AuditResultNode(details instanceof Array ? details : [details]);
  497. var request = {
  498. command: commands.AddAuditResult,
  499. resultId: this._id,
  500. displayName: displayName,
  501. description: description,
  502. severity: severity,
  503. details: details
  504. };
  505. extensionServer.sendRequest(request);
  506. },
  507. createResult: function()
  508. {
  509. return new AuditResultNode(Array.prototype.slice.call(arguments));
  510. },
  511. updateProgress: function(worked, totalWork)
  512. {
  513. extensionServer.sendRequest({ command: commands.UpdateAuditProgress, resultId: this._id, progress: worked / totalWork });
  514. },
  515. done: function()
  516. {
  517. extensionServer.sendRequest({ command: commands.StopAuditCategoryRun, resultId: this._id });
  518. },
  519. get Severity()
  520. {
  521. return apiPrivate.audits.Severity;
  522. },
  523. createResourceLink: function(url, lineNumber)
  524. {
  525. return {
  526. type: "resourceLink",
  527. arguments: [url, lineNumber && lineNumber - 1]
  528. };
  529. },
  530. _nodeFactory: function(type)
  531. {
  532. return {
  533. type: type,
  534. arguments: Array.prototype.slice.call(arguments, 1)
  535. };
  536. }
  537. }
  538. /**
  539. * @constructor
  540. */
  541. function AuditResultNode(contents)
  542. {
  543. this.contents = contents;
  544. this.children = [];
  545. this.expanded = false;
  546. }
  547. AuditResultNode.prototype = {
  548. addChild: function()
  549. {
  550. var node = new AuditResultNode(Array.prototype.slice.call(arguments));
  551. this.children.push(node);
  552. return node;
  553. }
  554. };
  555. /**
  556. * @constructor
  557. */
  558. function InspectedWindow()
  559. {
  560. function dispatchResourceEvent(message)
  561. {
  562. this._fire(new Resource(message.arguments[0]));
  563. }
  564. function dispatchResourceContentEvent(message)
  565. {
  566. this._fire(new Resource(message.arguments[0]), message.arguments[1]);
  567. }
  568. this.onResourceAdded = new EventSink(events.ResourceAdded, dispatchResourceEvent);
  569. this.onResourceContentCommitted = new EventSink(events.ResourceContentCommitted, dispatchResourceContentEvent);
  570. }
  571. InspectedWindow.prototype = {
  572. reload: function(optionsOrUserAgent)
  573. {
  574. var options = null;
  575. if (typeof optionsOrUserAgent === "object")
  576. options = optionsOrUserAgent;
  577. else if (typeof optionsOrUserAgent === "string") {
  578. options = { userAgent: optionsOrUserAgent };
  579. console.warn("Passing userAgent as string parameter to inspectedWindow.reload() is deprecated. " +
  580. "Use inspectedWindow.reload({ userAgent: value}) instead.");
  581. }
  582. return extensionServer.sendRequest({ command: commands.Reload, options: options });
  583. },
  584. eval: function(expression, evaluateOptions)
  585. {
  586. var callback = extractCallbackArgument(arguments);
  587. function callbackWrapper(result)
  588. {
  589. if (result.isError || result.isException)
  590. callback(undefined, result);
  591. else
  592. callback(result.value);
  593. }
  594. var request = {
  595. command: commands.EvaluateOnInspectedPage,
  596. expression: expression
  597. };
  598. if (typeof evaluateOptions === "object")
  599. request.evaluateOptions = evaluateOptions;
  600. return extensionServer.sendRequest(request, callback && callbackWrapper);
  601. },
  602. getResources: function(callback)
  603. {
  604. function wrapResource(resourceData)
  605. {
  606. return new Resource(resourceData);
  607. }
  608. function callbackWrapper(resources)
  609. {
  610. callback(resources.map(wrapResource));
  611. }
  612. return extensionServer.sendRequest({ command: commands.GetPageResources }, callback && callbackWrapper);
  613. }
  614. }
  615. /**
  616. * @constructor
  617. */
  618. function ResourceImpl(resourceData)
  619. {
  620. this._url = resourceData.url
  621. this._type = resourceData.type;
  622. }
  623. ResourceImpl.prototype = {
  624. get url()
  625. {
  626. return this._url;
  627. },
  628. get type()
  629. {
  630. return this._type;
  631. },
  632. getContent: function(callback)
  633. {
  634. function callbackWrapper(response)
  635. {
  636. callback(response.content, response.encoding);
  637. }
  638. return extensionServer.sendRequest({ command: commands.GetResourceContent, url: this._url }, callback && callbackWrapper);
  639. },
  640. setContent: function(content, commit, callback)
  641. {
  642. return extensionServer.sendRequest({ command: commands.SetResourceContent, url: this._url, content: content, commit: commit }, callback);
  643. }
  644. }
  645. /**
  646. * @constructor
  647. */
  648. function TimelineImpl()
  649. {
  650. this.onEventRecorded = new EventSink(events.TimelineEventRecorded);
  651. }
  652. /**
  653. * @constructor
  654. */
  655. function ExtensionServerClient()
  656. {
  657. this._callbacks = {};
  658. this._handlers = {};
  659. this._lastRequestId = 0;
  660. this._lastObjectId = 0;
  661. this.registerHandler("callback", this._onCallback.bind(this));
  662. var channel = new MessageChannel();
  663. this._port = channel.port1;
  664. this._port.addEventListener("message", this._onMessage.bind(this), false);
  665. this._port.start();
  666. window.parent.postMessage("registerExtension", [ channel.port2 ], "*");
  667. }
  668. ExtensionServerClient.prototype = {
  669. /**
  670. * @param {function()=} callback
  671. */
  672. sendRequest: function(message, callback)
  673. {
  674. if (typeof callback === "function")
  675. message.requestId = this._registerCallback(callback);
  676. return this._port.postMessage(message);
  677. },
  678. hasHandler: function(command)
  679. {
  680. return !!this._handlers[command];
  681. },
  682. registerHandler: function(command, handler)
  683. {
  684. this._handlers[command] = handler;
  685. },
  686. unregisterHandler: function(command)
  687. {
  688. delete this._handlers[command];
  689. },
  690. nextObjectId: function()
  691. {
  692. return injectedScriptId + "_" + ++this._lastObjectId;
  693. },
  694. _registerCallback: function(callback)
  695. {
  696. var id = ++this._lastRequestId;
  697. this._callbacks[id] = callback;
  698. return id;
  699. },
  700. _onCallback: function(request)
  701. {
  702. if (request.requestId in this._callbacks) {
  703. var callback = this._callbacks[request.requestId];
  704. delete this._callbacks[request.requestId];
  705. callback(request.result);
  706. }
  707. },
  708. _onMessage: function(event)
  709. {
  710. var request = event.data;
  711. var handler = this._handlers[request.command];
  712. if (handler)
  713. handler.call(this, request);
  714. }
  715. }
  716. function populateInterfaceClass(interface, implementation)
  717. {
  718. for (var member in implementation) {
  719. if (member.charAt(0) === "_")
  720. continue;
  721. var descriptor = null;
  722. // Traverse prototype chain until we find the owner.
  723. for (var owner = implementation; owner && !descriptor; owner = owner.__proto__)
  724. descriptor = Object.getOwnPropertyDescriptor(owner, member);
  725. if (!descriptor)
  726. continue;
  727. if (typeof descriptor.value === "function")
  728. interface[member] = descriptor.value.bind(implementation);
  729. else if (typeof descriptor.get === "function")
  730. interface.__defineGetter__(member, descriptor.get.bind(implementation));
  731. else
  732. Object.defineProperty(interface, member, descriptor);
  733. }
  734. }
  735. function declareInterfaceClass(implConstructor)
  736. {
  737. return function()
  738. {
  739. var impl = { __proto__: implConstructor.prototype };
  740. implConstructor.apply(impl, arguments);
  741. populateInterfaceClass(this, impl);
  742. }
  743. }
  744. function defineDeprecatedProperty(object, className, oldName, newName)
  745. {
  746. var warningGiven = false;
  747. function getter()
  748. {
  749. if (!warningGiven) {
  750. console.warn(className + "." + oldName + " is deprecated. Use " + className + "." + newName + " instead");
  751. warningGiven = true;
  752. }
  753. return object[newName];
  754. }
  755. object.__defineGetter__(oldName, getter);
  756. }
  757. function extractCallbackArgument(args)
  758. {
  759. var lastArgument = args[args.length - 1];
  760. return typeof lastArgument === "function" ? lastArgument : undefined;
  761. }
  762. var AuditCategory = declareInterfaceClass(AuditCategoryImpl);
  763. var AuditResult = declareInterfaceClass(AuditResultImpl);
  764. var Button = declareInterfaceClass(ButtonImpl);
  765. var EventSink = declareInterfaceClass(EventSinkImpl);
  766. var ExtensionPanel = declareInterfaceClass(ExtensionPanelImpl);
  767. var ExtensionSidebarPane = declareInterfaceClass(ExtensionSidebarPaneImpl);
  768. var PanelWithSidebar = declareInterfaceClass(PanelWithSidebarImpl);
  769. var Request = declareInterfaceClass(RequestImpl);
  770. var Resource = declareInterfaceClass(ResourceImpl);
  771. var Timeline = declareInterfaceClass(TimelineImpl);
  772. // extensionServer is a closure variable defined by the glue below -- make sure we fail if it's not there.
  773. if (!extensionServer)
  774. extensionServer = new ExtensionServerClient();
  775. return new InspectorExtensionAPI();
  776. }
  777. // Default implementation; platforms will override.
  778. function buildPlatformExtensionAPI(extensionInfo)
  779. {
  780. function platformExtensionAPI(coreAPI)
  781. {
  782. window.webInspector = coreAPI;
  783. }
  784. return platformExtensionAPI.toString();
  785. }
  786. function buildExtensionAPIInjectedScript(extensionInfo)
  787. {
  788. return "(function(injectedScriptId){ " +
  789. "var extensionServer;" +
  790. defineCommonExtensionSymbols.toString() + ";" +
  791. injectedExtensionAPI.toString() + ";" +
  792. buildPlatformExtensionAPI(extensionInfo) + ";" +
  793. "platformExtensionAPI(injectedExtensionAPI(injectedScriptId));" +
  794. "return {};" +
  795. "})";
  796. }