PageRenderTime 57ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/files/zeroclipboard/2.1.6/ZeroClipboard.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 1547 lines | 1166 code | 13 blank | 368 comment | 431 complexity | f579660f24a1e32ff640e427c62cf226 MD5 | raw file
  1. /*!
  2. * ZeroClipboard
  3. * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.
  4. * Copyright (c) 2014 Jon Rohan, James M. Greene
  5. * Licensed MIT
  6. * http://zeroclipboard.org/
  7. * v2.1.6
  8. */
  9. (function(window, undefined) {
  10. "use strict";
  11. /**
  12. * Store references to critically important global functions that may be
  13. * overridden on certain web pages.
  14. */
  15. var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _round = _window.Math.round, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice, _unwrap = function() {
  16. var unwrapper = function(el) {
  17. return el;
  18. };
  19. if (typeof _window.wrap === "function" && typeof _window.unwrap === "function") {
  20. try {
  21. var div = _document.createElement("div");
  22. var unwrappedDiv = _window.unwrap(div);
  23. if (div.nodeType === 1 && unwrappedDiv && unwrappedDiv.nodeType === 1) {
  24. unwrapper = _window.unwrap;
  25. }
  26. } catch (e) {}
  27. }
  28. return unwrapper;
  29. }();
  30. /**
  31. * Convert an `arguments` object into an Array.
  32. *
  33. * @returns The arguments as an Array
  34. * @private
  35. */
  36. var _args = function(argumentsObj) {
  37. return _slice.call(argumentsObj, 0);
  38. };
  39. /**
  40. * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`.
  41. *
  42. * @returns The target object, augmented
  43. * @private
  44. */
  45. var _extend = function() {
  46. var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {};
  47. for (i = 1, len = args.length; i < len; i++) {
  48. if ((arg = args[i]) != null) {
  49. for (prop in arg) {
  50. if (_hasOwn.call(arg, prop)) {
  51. src = target[prop];
  52. copy = arg[prop];
  53. if (target !== copy && copy !== undefined) {
  54. target[prop] = copy;
  55. }
  56. }
  57. }
  58. }
  59. }
  60. return target;
  61. };
  62. /**
  63. * Return a deep copy of the source object or array.
  64. *
  65. * @returns Object or Array
  66. * @private
  67. */
  68. var _deepCopy = function(source) {
  69. var copy, i, len, prop;
  70. if (typeof source !== "object" || source == null) {
  71. copy = source;
  72. } else if (typeof source.length === "number") {
  73. copy = [];
  74. for (i = 0, len = source.length; i < len; i++) {
  75. if (_hasOwn.call(source, i)) {
  76. copy[i] = _deepCopy(source[i]);
  77. }
  78. }
  79. } else {
  80. copy = {};
  81. for (prop in source) {
  82. if (_hasOwn.call(source, prop)) {
  83. copy[prop] = _deepCopy(source[prop]);
  84. }
  85. }
  86. }
  87. return copy;
  88. };
  89. /**
  90. * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep.
  91. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to
  92. * be kept.
  93. *
  94. * @returns A new filtered object.
  95. * @private
  96. */
  97. var _pick = function(obj, keys) {
  98. var newObj = {};
  99. for (var i = 0, len = keys.length; i < len; i++) {
  100. if (keys[i] in obj) {
  101. newObj[keys[i]] = obj[keys[i]];
  102. }
  103. }
  104. return newObj;
  105. };
  106. /**
  107. * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit.
  108. * The inverse of `_pick`.
  109. *
  110. * @returns A new filtered object.
  111. * @private
  112. */
  113. var _omit = function(obj, keys) {
  114. var newObj = {};
  115. for (var prop in obj) {
  116. if (keys.indexOf(prop) === -1) {
  117. newObj[prop] = obj[prop];
  118. }
  119. }
  120. return newObj;
  121. };
  122. /**
  123. * Remove all owned, enumerable properties from an object.
  124. *
  125. * @returns The original object without its owned, enumerable properties.
  126. * @private
  127. */
  128. var _deleteOwnProperties = function(obj) {
  129. if (obj) {
  130. for (var prop in obj) {
  131. if (_hasOwn.call(obj, prop)) {
  132. delete obj[prop];
  133. }
  134. }
  135. }
  136. return obj;
  137. };
  138. /**
  139. * Determine if an element is contained within another element.
  140. *
  141. * @returns Boolean
  142. * @private
  143. */
  144. var _containedBy = function(el, ancestorEl) {
  145. if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) {
  146. do {
  147. if (el === ancestorEl) {
  148. return true;
  149. }
  150. el = el.parentNode;
  151. } while (el);
  152. }
  153. return false;
  154. };
  155. /**
  156. * Get the URL path's parent directory.
  157. *
  158. * @returns String or `undefined`
  159. * @private
  160. */
  161. var _getDirPathOfUrl = function(url) {
  162. var dir;
  163. if (typeof url === "string" && url) {
  164. dir = url.split("#")[0].split("?")[0];
  165. dir = url.slice(0, url.lastIndexOf("/") + 1);
  166. }
  167. return dir;
  168. };
  169. /**
  170. * Get the current script's URL by throwing an `Error` and analyzing it.
  171. *
  172. * @returns String or `undefined`
  173. * @private
  174. */
  175. var _getCurrentScriptUrlFromErrorStack = function(stack) {
  176. var url, matches;
  177. if (typeof stack === "string" && stack) {
  178. matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
  179. if (matches && matches[1]) {
  180. url = matches[1];
  181. } else {
  182. matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
  183. if (matches && matches[1]) {
  184. url = matches[1];
  185. }
  186. }
  187. }
  188. return url;
  189. };
  190. /**
  191. * Get the current script's URL by throwing an `Error` and analyzing it.
  192. *
  193. * @returns String or `undefined`
  194. * @private
  195. */
  196. var _getCurrentScriptUrlFromError = function() {
  197. var url, err;
  198. try {
  199. throw new _Error();
  200. } catch (e) {
  201. err = e;
  202. }
  203. if (err) {
  204. url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack);
  205. }
  206. return url;
  207. };
  208. /**
  209. * Get the current script's URL.
  210. *
  211. * @returns String or `undefined`
  212. * @private
  213. */
  214. var _getCurrentScriptUrl = function() {
  215. var jsPath, scripts, i;
  216. if (_document.currentScript && (jsPath = _document.currentScript.src)) {
  217. return jsPath;
  218. }
  219. scripts = _document.getElementsByTagName("script");
  220. if (scripts.length === 1) {
  221. return scripts[0].src || undefined;
  222. }
  223. if ("readyState" in scripts[0]) {
  224. for (i = scripts.length; i--; ) {
  225. if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) {
  226. return jsPath;
  227. }
  228. }
  229. }
  230. if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) {
  231. return jsPath;
  232. }
  233. if (jsPath = _getCurrentScriptUrlFromError()) {
  234. return jsPath;
  235. }
  236. return undefined;
  237. };
  238. /**
  239. * Get the unanimous parent directory of ALL script tags.
  240. * If any script tags are either (a) inline or (b) from differing parent
  241. * directories, this method must return `undefined`.
  242. *
  243. * @returns String or `undefined`
  244. * @private
  245. */
  246. var _getUnanimousScriptParentDir = function() {
  247. var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script");
  248. for (i = scripts.length; i--; ) {
  249. if (!(jsPath = scripts[i].src)) {
  250. jsDir = null;
  251. break;
  252. }
  253. jsPath = _getDirPathOfUrl(jsPath);
  254. if (jsDir == null) {
  255. jsDir = jsPath;
  256. } else if (jsDir !== jsPath) {
  257. jsDir = null;
  258. break;
  259. }
  260. }
  261. return jsDir || undefined;
  262. };
  263. /**
  264. * Get the presumed location of the "ZeroClipboard.swf" file, based on the location
  265. * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.).
  266. *
  267. * @returns String
  268. * @private
  269. */
  270. var _getDefaultSwfPath = function() {
  271. var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || "";
  272. return jsDir + "ZeroClipboard.swf";
  273. };
  274. /**
  275. * Keep track of the state of the Flash object.
  276. * @private
  277. */
  278. var _flashState = {
  279. bridge: null,
  280. version: "0.0.0",
  281. pluginType: "unknown",
  282. disabled: null,
  283. outdated: null,
  284. unavailable: null,
  285. deactivated: null,
  286. overdue: null,
  287. ready: null
  288. };
  289. /**
  290. * The minimum Flash Player version required to use ZeroClipboard completely.
  291. * @readonly
  292. * @private
  293. */
  294. var _minimumFlashVersion = "11.0.0";
  295. /**
  296. * Keep track of all event listener registrations.
  297. * @private
  298. */
  299. var _handlers = {};
  300. /**
  301. * Keep track of the currently activated element.
  302. * @private
  303. */
  304. var _currentElement;
  305. /**
  306. * Keep track of the element that was activated when a `copy` process started.
  307. * @private
  308. */
  309. var _copyTarget;
  310. /**
  311. * Keep track of data for the pending clipboard transaction.
  312. * @private
  313. */
  314. var _clipData = {};
  315. /**
  316. * Keep track of data formats for the pending clipboard transaction.
  317. * @private
  318. */
  319. var _clipDataFormatMap = null;
  320. /**
  321. * The `message` store for events
  322. * @private
  323. */
  324. var _eventMessages = {
  325. ready: "Flash communication is established",
  326. error: {
  327. "flash-disabled": "Flash is disabled or not installed",
  328. "flash-outdated": "Flash is too outdated to support ZeroClipboard",
  329. "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript",
  330. "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate",
  331. "flash-overdue": "Flash communication was established but NOT within the acceptable time limit"
  332. }
  333. };
  334. /**
  335. * ZeroClipboard configuration defaults for the Core module.
  336. * @private
  337. */
  338. var _globalConfig = {
  339. swfPath: _getDefaultSwfPath(),
  340. trustedDomains: window.location.host ? [ window.location.host ] : [],
  341. cacheBust: true,
  342. forceEnhancedClipboard: false,
  343. flashLoadTimeout: 3e4,
  344. autoActivate: true,
  345. bubbleEvents: true,
  346. containerId: "global-zeroclipboard-html-bridge",
  347. containerClass: "global-zeroclipboard-container",
  348. swfObjectId: "global-zeroclipboard-flash-bridge",
  349. hoverClass: "zeroclipboard-is-hover",
  350. activeClass: "zeroclipboard-is-active",
  351. forceHandCursor: false,
  352. title: null,
  353. zIndex: 999999999
  354. };
  355. /**
  356. * The underlying implementation of `ZeroClipboard.config`.
  357. * @private
  358. */
  359. var _config = function(options) {
  360. if (typeof options === "object" && options !== null) {
  361. for (var prop in options) {
  362. if (_hasOwn.call(options, prop)) {
  363. if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) {
  364. _globalConfig[prop] = options[prop];
  365. } else if (_flashState.bridge == null) {
  366. if (prop === "containerId" || prop === "swfObjectId") {
  367. if (_isValidHtml4Id(options[prop])) {
  368. _globalConfig[prop] = options[prop];
  369. } else {
  370. throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID");
  371. }
  372. } else {
  373. _globalConfig[prop] = options[prop];
  374. }
  375. }
  376. }
  377. }
  378. }
  379. if (typeof options === "string" && options) {
  380. if (_hasOwn.call(_globalConfig, options)) {
  381. return _globalConfig[options];
  382. }
  383. return;
  384. }
  385. return _deepCopy(_globalConfig);
  386. };
  387. /**
  388. * The underlying implementation of `ZeroClipboard.state`.
  389. * @private
  390. */
  391. var _state = function() {
  392. return {
  393. browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]),
  394. flash: _omit(_flashState, [ "bridge" ]),
  395. zeroclipboard: {
  396. version: ZeroClipboard.version,
  397. config: ZeroClipboard.config()
  398. }
  399. };
  400. };
  401. /**
  402. * The underlying implementation of `ZeroClipboard.isFlashUnusable`.
  403. * @private
  404. */
  405. var _isFlashUnusable = function() {
  406. return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated);
  407. };
  408. /**
  409. * The underlying implementation of `ZeroClipboard.on`.
  410. * @private
  411. */
  412. var _on = function(eventType, listener) {
  413. var i, len, events, added = {};
  414. if (typeof eventType === "string" && eventType) {
  415. events = eventType.toLowerCase().split(/\s+/);
  416. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  417. for (i in eventType) {
  418. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  419. ZeroClipboard.on(i, eventType[i]);
  420. }
  421. }
  422. }
  423. if (events && events.length) {
  424. for (i = 0, len = events.length; i < len; i++) {
  425. eventType = events[i].replace(/^on/, "");
  426. added[eventType] = true;
  427. if (!_handlers[eventType]) {
  428. _handlers[eventType] = [];
  429. }
  430. _handlers[eventType].push(listener);
  431. }
  432. if (added.ready && _flashState.ready) {
  433. ZeroClipboard.emit({
  434. type: "ready"
  435. });
  436. }
  437. if (added.error) {
  438. var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ];
  439. for (i = 0, len = errorTypes.length; i < len; i++) {
  440. if (_flashState[errorTypes[i]] === true) {
  441. ZeroClipboard.emit({
  442. type: "error",
  443. name: "flash-" + errorTypes[i]
  444. });
  445. break;
  446. }
  447. }
  448. }
  449. }
  450. return ZeroClipboard;
  451. };
  452. /**
  453. * The underlying implementation of `ZeroClipboard.off`.
  454. * @private
  455. */
  456. var _off = function(eventType, listener) {
  457. var i, len, foundIndex, events, perEventHandlers;
  458. if (arguments.length === 0) {
  459. events = _keys(_handlers);
  460. } else if (typeof eventType === "string" && eventType) {
  461. events = eventType.split(/\s+/);
  462. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  463. for (i in eventType) {
  464. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  465. ZeroClipboard.off(i, eventType[i]);
  466. }
  467. }
  468. }
  469. if (events && events.length) {
  470. for (i = 0, len = events.length; i < len; i++) {
  471. eventType = events[i].toLowerCase().replace(/^on/, "");
  472. perEventHandlers = _handlers[eventType];
  473. if (perEventHandlers && perEventHandlers.length) {
  474. if (listener) {
  475. foundIndex = perEventHandlers.indexOf(listener);
  476. while (foundIndex !== -1) {
  477. perEventHandlers.splice(foundIndex, 1);
  478. foundIndex = perEventHandlers.indexOf(listener, foundIndex);
  479. }
  480. } else {
  481. perEventHandlers.length = 0;
  482. }
  483. }
  484. }
  485. }
  486. return ZeroClipboard;
  487. };
  488. /**
  489. * The underlying implementation of `ZeroClipboard.handlers`.
  490. * @private
  491. */
  492. var _listeners = function(eventType) {
  493. var copy;
  494. if (typeof eventType === "string" && eventType) {
  495. copy = _deepCopy(_handlers[eventType]) || null;
  496. } else {
  497. copy = _deepCopy(_handlers);
  498. }
  499. return copy;
  500. };
  501. /**
  502. * The underlying implementation of `ZeroClipboard.emit`.
  503. * @private
  504. */
  505. var _emit = function(event) {
  506. var eventCopy, returnVal, tmp;
  507. event = _createEvent(event);
  508. if (!event) {
  509. return;
  510. }
  511. if (_preprocessEvent(event)) {
  512. return;
  513. }
  514. if (event.type === "ready" && _flashState.overdue === true) {
  515. return ZeroClipboard.emit({
  516. type: "error",
  517. name: "flash-overdue"
  518. });
  519. }
  520. eventCopy = _extend({}, event);
  521. _dispatchCallbacks.call(this, eventCopy);
  522. if (event.type === "copy") {
  523. tmp = _mapClipDataToFlash(_clipData);
  524. returnVal = tmp.data;
  525. _clipDataFormatMap = tmp.formatMap;
  526. }
  527. return returnVal;
  528. };
  529. /**
  530. * The underlying implementation of `ZeroClipboard.create`.
  531. * @private
  532. */
  533. var _create = function() {
  534. if (typeof _flashState.ready !== "boolean") {
  535. _flashState.ready = false;
  536. }
  537. if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) {
  538. var maxWait = _globalConfig.flashLoadTimeout;
  539. if (typeof maxWait === "number" && maxWait >= 0) {
  540. _setTimeout(function() {
  541. if (typeof _flashState.deactivated !== "boolean") {
  542. _flashState.deactivated = true;
  543. }
  544. if (_flashState.deactivated === true) {
  545. ZeroClipboard.emit({
  546. type: "error",
  547. name: "flash-deactivated"
  548. });
  549. }
  550. }, maxWait);
  551. }
  552. _flashState.overdue = false;
  553. _embedSwf();
  554. }
  555. };
  556. /**
  557. * The underlying implementation of `ZeroClipboard.destroy`.
  558. * @private
  559. */
  560. var _destroy = function() {
  561. ZeroClipboard.clearData();
  562. ZeroClipboard.blur();
  563. ZeroClipboard.emit("destroy");
  564. _unembedSwf();
  565. ZeroClipboard.off();
  566. };
  567. /**
  568. * The underlying implementation of `ZeroClipboard.setData`.
  569. * @private
  570. */
  571. var _setData = function(format, data) {
  572. var dataObj;
  573. if (typeof format === "object" && format && typeof data === "undefined") {
  574. dataObj = format;
  575. ZeroClipboard.clearData();
  576. } else if (typeof format === "string" && format) {
  577. dataObj = {};
  578. dataObj[format] = data;
  579. } else {
  580. return;
  581. }
  582. for (var dataFormat in dataObj) {
  583. if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) {
  584. _clipData[dataFormat] = dataObj[dataFormat];
  585. }
  586. }
  587. };
  588. /**
  589. * The underlying implementation of `ZeroClipboard.clearData`.
  590. * @private
  591. */
  592. var _clearData = function(format) {
  593. if (typeof format === "undefined") {
  594. _deleteOwnProperties(_clipData);
  595. _clipDataFormatMap = null;
  596. } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
  597. delete _clipData[format];
  598. }
  599. };
  600. /**
  601. * The underlying implementation of `ZeroClipboard.getData`.
  602. * @private
  603. */
  604. var _getData = function(format) {
  605. if (typeof format === "undefined") {
  606. return _deepCopy(_clipData);
  607. } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
  608. return _clipData[format];
  609. }
  610. };
  611. /**
  612. * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`.
  613. * @private
  614. */
  615. var _focus = function(element) {
  616. if (!(element && element.nodeType === 1)) {
  617. return;
  618. }
  619. if (_currentElement) {
  620. _removeClass(_currentElement, _globalConfig.activeClass);
  621. if (_currentElement !== element) {
  622. _removeClass(_currentElement, _globalConfig.hoverClass);
  623. }
  624. }
  625. _currentElement = element;
  626. _addClass(element, _globalConfig.hoverClass);
  627. var newTitle = element.getAttribute("title") || _globalConfig.title;
  628. if (typeof newTitle === "string" && newTitle) {
  629. var htmlBridge = _getHtmlBridge(_flashState.bridge);
  630. if (htmlBridge) {
  631. htmlBridge.setAttribute("title", newTitle);
  632. }
  633. }
  634. var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer";
  635. _setHandCursor(useHandCursor);
  636. _reposition();
  637. };
  638. /**
  639. * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`.
  640. * @private
  641. */
  642. var _blur = function() {
  643. var htmlBridge = _getHtmlBridge(_flashState.bridge);
  644. if (htmlBridge) {
  645. htmlBridge.removeAttribute("title");
  646. htmlBridge.style.left = "0px";
  647. htmlBridge.style.top = "-9999px";
  648. htmlBridge.style.width = "1px";
  649. htmlBridge.style.top = "1px";
  650. }
  651. if (_currentElement) {
  652. _removeClass(_currentElement, _globalConfig.hoverClass);
  653. _removeClass(_currentElement, _globalConfig.activeClass);
  654. _currentElement = null;
  655. }
  656. };
  657. /**
  658. * The underlying implementation of `ZeroClipboard.activeElement`.
  659. * @private
  660. */
  661. var _activeElement = function() {
  662. return _currentElement || null;
  663. };
  664. /**
  665. * Check if a value is a valid HTML4 `ID` or `Name` token.
  666. * @private
  667. */
  668. var _isValidHtml4Id = function(id) {
  669. return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id);
  670. };
  671. /**
  672. * Create or update an `event` object, based on the `eventType`.
  673. * @private
  674. */
  675. var _createEvent = function(event) {
  676. var eventType;
  677. if (typeof event === "string" && event) {
  678. eventType = event;
  679. event = {};
  680. } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
  681. eventType = event.type;
  682. }
  683. if (!eventType) {
  684. return;
  685. }
  686. if (!event.target && /^(copy|aftercopy|_click)$/.test(eventType.toLowerCase())) {
  687. event.target = _copyTarget;
  688. }
  689. _extend(event, {
  690. type: eventType.toLowerCase(),
  691. target: event.target || _currentElement || null,
  692. relatedTarget: event.relatedTarget || null,
  693. currentTarget: _flashState && _flashState.bridge || null,
  694. timeStamp: event.timeStamp || _now() || null
  695. });
  696. var msg = _eventMessages[event.type];
  697. if (event.type === "error" && event.name && msg) {
  698. msg = msg[event.name];
  699. }
  700. if (msg) {
  701. event.message = msg;
  702. }
  703. if (event.type === "ready") {
  704. _extend(event, {
  705. target: null,
  706. version: _flashState.version
  707. });
  708. }
  709. if (event.type === "error") {
  710. if (/^flash-(disabled|outdated|unavailable|deactivated|overdue)$/.test(event.name)) {
  711. _extend(event, {
  712. target: null,
  713. minimumVersion: _minimumFlashVersion
  714. });
  715. }
  716. if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) {
  717. _extend(event, {
  718. version: _flashState.version
  719. });
  720. }
  721. }
  722. if (event.type === "copy") {
  723. event.clipboardData = {
  724. setData: ZeroClipboard.setData,
  725. clearData: ZeroClipboard.clearData
  726. };
  727. }
  728. if (event.type === "aftercopy") {
  729. event = _mapClipResultsFromFlash(event, _clipDataFormatMap);
  730. }
  731. if (event.target && !event.relatedTarget) {
  732. event.relatedTarget = _getRelatedTarget(event.target);
  733. }
  734. event = _addMouseData(event);
  735. return event;
  736. };
  737. /**
  738. * Get a relatedTarget from the target's `data-clipboard-target` attribute
  739. * @private
  740. */
  741. var _getRelatedTarget = function(targetEl) {
  742. var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target");
  743. return relatedTargetId ? _document.getElementById(relatedTargetId) : null;
  744. };
  745. /**
  746. * Add element and position data to `MouseEvent` instances
  747. * @private
  748. */
  749. var _addMouseData = function(event) {
  750. if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
  751. var srcElement = event.target;
  752. var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined;
  753. var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined;
  754. var pos = _getDOMObjectPosition(srcElement);
  755. var screenLeft = _window.screenLeft || _window.screenX || 0;
  756. var screenTop = _window.screenTop || _window.screenY || 0;
  757. var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft;
  758. var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop;
  759. var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0);
  760. var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0);
  761. var clientX = pageX - scrollLeft;
  762. var clientY = pageY - scrollTop;
  763. var screenX = screenLeft + clientX;
  764. var screenY = screenTop + clientY;
  765. var moveX = typeof event.movementX === "number" ? event.movementX : 0;
  766. var moveY = typeof event.movementY === "number" ? event.movementY : 0;
  767. delete event._stageX;
  768. delete event._stageY;
  769. _extend(event, {
  770. srcElement: srcElement,
  771. fromElement: fromElement,
  772. toElement: toElement,
  773. screenX: screenX,
  774. screenY: screenY,
  775. pageX: pageX,
  776. pageY: pageY,
  777. clientX: clientX,
  778. clientY: clientY,
  779. x: clientX,
  780. y: clientY,
  781. movementX: moveX,
  782. movementY: moveY,
  783. offsetX: 0,
  784. offsetY: 0,
  785. layerX: 0,
  786. layerY: 0
  787. });
  788. }
  789. return event;
  790. };
  791. /**
  792. * Determine if an event's registered handlers should be execute synchronously or asynchronously.
  793. *
  794. * @returns {boolean}
  795. * @private
  796. */
  797. var _shouldPerformAsync = function(event) {
  798. var eventType = event && typeof event.type === "string" && event.type || "";
  799. return !/^(?:(?:before)?copy|destroy)$/.test(eventType);
  800. };
  801. /**
  802. * Control if a callback should be executed asynchronously or not.
  803. *
  804. * @returns `undefined`
  805. * @private
  806. */
  807. var _dispatchCallback = function(func, context, args, async) {
  808. if (async) {
  809. _setTimeout(function() {
  810. func.apply(context, args);
  811. }, 0);
  812. } else {
  813. func.apply(context, args);
  814. }
  815. };
  816. /**
  817. * Handle the actual dispatching of events to client instances.
  818. *
  819. * @returns `undefined`
  820. * @private
  821. */
  822. var _dispatchCallbacks = function(event) {
  823. if (!(typeof event === "object" && event && event.type)) {
  824. return;
  825. }
  826. var async = _shouldPerformAsync(event);
  827. var wildcardTypeHandlers = _handlers["*"] || [];
  828. var specificTypeHandlers = _handlers[event.type] || [];
  829. var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
  830. if (handlers && handlers.length) {
  831. var i, len, func, context, eventCopy, originalContext = this;
  832. for (i = 0, len = handlers.length; i < len; i++) {
  833. func = handlers[i];
  834. context = originalContext;
  835. if (typeof func === "string" && typeof _window[func] === "function") {
  836. func = _window[func];
  837. }
  838. if (typeof func === "object" && func && typeof func.handleEvent === "function") {
  839. context = func;
  840. func = func.handleEvent;
  841. }
  842. if (typeof func === "function") {
  843. eventCopy = _extend({}, event);
  844. _dispatchCallback(func, context, [ eventCopy ], async);
  845. }
  846. }
  847. }
  848. return this;
  849. };
  850. /**
  851. * Preprocess any special behaviors, reactions, or state changes after receiving this event.
  852. * Executes only once per event emitted, NOT once per client.
  853. * @private
  854. */
  855. var _preprocessEvent = function(event) {
  856. var element = event.target || _currentElement || null;
  857. var sourceIsSwf = event._source === "swf";
  858. delete event._source;
  859. var flashErrorNames = [ "flash-disabled", "flash-outdated", "flash-unavailable", "flash-deactivated", "flash-overdue" ];
  860. switch (event.type) {
  861. case "error":
  862. if (flashErrorNames.indexOf(event.name) !== -1) {
  863. _extend(_flashState, {
  864. disabled: event.name === "flash-disabled",
  865. outdated: event.name === "flash-outdated",
  866. unavailable: event.name === "flash-unavailable",
  867. deactivated: event.name === "flash-deactivated",
  868. overdue: event.name === "flash-overdue",
  869. ready: false
  870. });
  871. }
  872. break;
  873. case "ready":
  874. var wasDeactivated = _flashState.deactivated === true;
  875. _extend(_flashState, {
  876. disabled: false,
  877. outdated: false,
  878. unavailable: false,
  879. deactivated: false,
  880. overdue: wasDeactivated,
  881. ready: !wasDeactivated
  882. });
  883. break;
  884. case "beforecopy":
  885. _copyTarget = element;
  886. break;
  887. case "copy":
  888. var textContent, htmlContent, targetEl = event.relatedTarget;
  889. if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) {
  890. event.clipboardData.clearData();
  891. event.clipboardData.setData("text/plain", textContent);
  892. if (htmlContent !== textContent) {
  893. event.clipboardData.setData("text/html", htmlContent);
  894. }
  895. } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) {
  896. event.clipboardData.clearData();
  897. event.clipboardData.setData("text/plain", textContent);
  898. }
  899. break;
  900. case "aftercopy":
  901. ZeroClipboard.clearData();
  902. if (element && element !== _safeActiveElement() && element.focus) {
  903. element.focus();
  904. }
  905. break;
  906. case "_mouseover":
  907. ZeroClipboard.focus(element);
  908. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  909. if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
  910. _fireMouseEvent(_extend({}, event, {
  911. type: "mouseenter",
  912. bubbles: false,
  913. cancelable: false
  914. }));
  915. }
  916. _fireMouseEvent(_extend({}, event, {
  917. type: "mouseover"
  918. }));
  919. }
  920. break;
  921. case "_mouseout":
  922. ZeroClipboard.blur();
  923. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  924. if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
  925. _fireMouseEvent(_extend({}, event, {
  926. type: "mouseleave",
  927. bubbles: false,
  928. cancelable: false
  929. }));
  930. }
  931. _fireMouseEvent(_extend({}, event, {
  932. type: "mouseout"
  933. }));
  934. }
  935. break;
  936. case "_mousedown":
  937. _addClass(element, _globalConfig.activeClass);
  938. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  939. _fireMouseEvent(_extend({}, event, {
  940. type: event.type.slice(1)
  941. }));
  942. }
  943. break;
  944. case "_mouseup":
  945. _removeClass(element, _globalConfig.activeClass);
  946. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  947. _fireMouseEvent(_extend({}, event, {
  948. type: event.type.slice(1)
  949. }));
  950. }
  951. break;
  952. case "_click":
  953. _copyTarget = null;
  954. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  955. _fireMouseEvent(_extend({}, event, {
  956. type: event.type.slice(1)
  957. }));
  958. }
  959. break;
  960. case "_mousemove":
  961. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  962. _fireMouseEvent(_extend({}, event, {
  963. type: event.type.slice(1)
  964. }));
  965. }
  966. break;
  967. }
  968. if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
  969. return true;
  970. }
  971. };
  972. /**
  973. * Dispatch a synthetic MouseEvent.
  974. *
  975. * @returns `undefined`
  976. * @private
  977. */
  978. var _fireMouseEvent = function(event) {
  979. if (!(event && typeof event.type === "string" && event)) {
  980. return;
  981. }
  982. var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = {
  983. view: doc.defaultView || _window,
  984. canBubble: true,
  985. cancelable: true,
  986. detail: event.type === "click" ? 1 : 0,
  987. button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1
  988. }, args = _extend(defaults, event);
  989. if (!target) {
  990. return;
  991. }
  992. if (doc.createEvent && target.dispatchEvent) {
  993. args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ];
  994. e = doc.createEvent("MouseEvents");
  995. if (e.initMouseEvent) {
  996. e.initMouseEvent.apply(e, args);
  997. e._source = "js";
  998. target.dispatchEvent(e);
  999. }
  1000. }
  1001. };
  1002. /**
  1003. * Create the HTML bridge element to embed the Flash object into.
  1004. * @private
  1005. */
  1006. var _createHtmlBridge = function() {
  1007. var container = _document.createElement("div");
  1008. container.id = _globalConfig.containerId;
  1009. container.className = _globalConfig.containerClass;
  1010. container.style.position = "absolute";
  1011. container.style.left = "0px";
  1012. container.style.top = "-9999px";
  1013. container.style.width = "1px";
  1014. container.style.height = "1px";
  1015. container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex);
  1016. return container;
  1017. };
  1018. /**
  1019. * Get the HTML element container that wraps the Flash bridge object/element.
  1020. * @private
  1021. */
  1022. var _getHtmlBridge = function(flashBridge) {
  1023. var htmlBridge = flashBridge && flashBridge.parentNode;
  1024. while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) {
  1025. htmlBridge = htmlBridge.parentNode;
  1026. }
  1027. return htmlBridge || null;
  1028. };
  1029. /**
  1030. * Create the SWF object.
  1031. *
  1032. * @returns The SWF object reference.
  1033. * @private
  1034. */
  1035. var _embedSwf = function() {
  1036. var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge);
  1037. if (!flashBridge) {
  1038. var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig);
  1039. var allowNetworking = allowScriptAccess === "never" ? "none" : "all";
  1040. var flashvars = _vars(_globalConfig);
  1041. var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig);
  1042. container = _createHtmlBridge();
  1043. var divToBeReplaced = _document.createElement("div");
  1044. container.appendChild(divToBeReplaced);
  1045. _document.body.appendChild(container);
  1046. var tmpDiv = _document.createElement("div");
  1047. var oldIE = _flashState.pluginType === "activex";
  1048. tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>";
  1049. flashBridge = tmpDiv.firstChild;
  1050. tmpDiv = null;
  1051. _unwrap(flashBridge).ZeroClipboard = ZeroClipboard;
  1052. container.replaceChild(flashBridge, divToBeReplaced);
  1053. }
  1054. if (!flashBridge) {
  1055. flashBridge = _document[_globalConfig.swfObjectId];
  1056. if (flashBridge && (len = flashBridge.length)) {
  1057. flashBridge = flashBridge[len - 1];
  1058. }
  1059. if (!flashBridge && container) {
  1060. flashBridge = container.firstChild;
  1061. }
  1062. }
  1063. _flashState.bridge = flashBridge || null;
  1064. return flashBridge;
  1065. };
  1066. /**
  1067. * Destroy the SWF object.
  1068. * @private
  1069. */
  1070. var _unembedSwf = function() {
  1071. var flashBridge = _flashState.bridge;
  1072. if (flashBridge) {
  1073. var htmlBridge = _getHtmlBridge(flashBridge);
  1074. if (htmlBridge) {
  1075. if (_flashState.pluginType === "activex" && "readyState" in flashBridge) {
  1076. flashBridge.style.display = "none";
  1077. (function removeSwfFromIE() {
  1078. if (flashBridge.readyState === 4) {
  1079. for (var prop in flashBridge) {
  1080. if (typeof flashBridge[prop] === "function") {
  1081. flashBridge[prop] = null;
  1082. }
  1083. }
  1084. if (flashBridge.parentNode) {
  1085. flashBridge.parentNode.removeChild(flashBridge);
  1086. }
  1087. if (htmlBridge.parentNode) {
  1088. htmlBridge.parentNode.removeChild(htmlBridge);
  1089. }
  1090. } else {
  1091. _setTimeout(removeSwfFromIE, 10);
  1092. }
  1093. })();
  1094. } else {
  1095. if (flashBridge.parentNode) {
  1096. flashBridge.parentNode.removeChild(flashBridge);
  1097. }
  1098. if (htmlBridge.parentNode) {
  1099. htmlBridge.parentNode.removeChild(htmlBridge);
  1100. }
  1101. }
  1102. }
  1103. _flashState.ready = null;
  1104. _flashState.bridge = null;
  1105. _flashState.deactivated = null;
  1106. }
  1107. };
  1108. /**
  1109. * Map the data format names of the "clipData" to Flash-friendly names.
  1110. *
  1111. * @returns A new transformed object.
  1112. * @private
  1113. */
  1114. var _mapClipDataToFlash = function(clipData) {
  1115. var newClipData = {}, formatMap = {};
  1116. if (!(typeof clipData === "object" && clipData)) {
  1117. return;
  1118. }
  1119. for (var dataFormat in clipData) {
  1120. if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) {
  1121. switch (dataFormat.toLowerCase()) {
  1122. case "text/plain":
  1123. case "text":
  1124. case "air:text":
  1125. case "flash:text":
  1126. newClipData.text = clipData[dataFormat];
  1127. formatMap.text = dataFormat;
  1128. break;
  1129. case "text/html":
  1130. case "html":
  1131. case "air:html":
  1132. case "flash:html":
  1133. newClipData.html = clipData[dataFormat];
  1134. formatMap.html = dataFormat;
  1135. break;
  1136. case "application/rtf":
  1137. case "text/rtf":
  1138. case "rtf":
  1139. case "richtext":
  1140. case "air:rtf":
  1141. case "flash:rtf":
  1142. newClipData.rtf = clipData[dataFormat];
  1143. formatMap.rtf = dataFormat;
  1144. break;
  1145. default:
  1146. break;
  1147. }
  1148. }
  1149. }
  1150. return {
  1151. data: newClipData,
  1152. formatMap: formatMap
  1153. };
  1154. };
  1155. /**
  1156. * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping).
  1157. *
  1158. * @returns A new transformed object.
  1159. * @private
  1160. */
  1161. var _mapClipResultsFromFlash = function(clipResults, formatMap) {
  1162. if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) {
  1163. return clipResults;
  1164. }
  1165. var newResults = {};
  1166. for (var prop in clipResults) {
  1167. if (_hasOwn.call(clipResults, prop)) {
  1168. if (prop !== "success" && prop !== "data") {
  1169. newResults[prop] = clipResults[prop];
  1170. continue;
  1171. }
  1172. newResults[prop] = {};
  1173. var tmpHash = clipResults[prop];
  1174. for (var dataFormat in tmpHash) {
  1175. if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) {
  1176. newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat];
  1177. }
  1178. }
  1179. }
  1180. }
  1181. return newResults;
  1182. };
  1183. /**
  1184. * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}"
  1185. * query param string to return. Does NOT append that string to the original path.
  1186. * This is useful because ExternalInterface often breaks when a Flash SWF is cached.
  1187. *
  1188. * @returns The `noCache` query param with necessary "?"/"&" prefix.
  1189. * @private
  1190. */
  1191. var _cacheBust = function(path, options) {
  1192. var cacheBust = options == null || options && options.cacheBust === true;
  1193. if (cacheBust) {
  1194. return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now();
  1195. } else {
  1196. return "";
  1197. }
  1198. };
  1199. /**
  1200. * Creates a query string for the FlashVars param.
  1201. * Does NOT include the cache-busting query param.
  1202. *
  1203. * @returns FlashVars query string
  1204. * @private
  1205. */
  1206. var _vars = function(options) {
  1207. var i, len, domain, domains, str = "", trustedOriginsExpanded = [];
  1208. if (options.trustedDomains) {
  1209. if (typeof options.trustedDomains === "string") {
  1210. domains = [ options.trustedDomains ];
  1211. } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
  1212. domains = options.trustedDomains;
  1213. }
  1214. }
  1215. if (domains && domains.length) {
  1216. for (i = 0, len = domains.length; i < len; i++) {
  1217. if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") {
  1218. domain = _extractDomain(domains[i]);
  1219. if (!domain) {
  1220. continue;
  1221. }
  1222. if (domain === "*") {
  1223. trustedOriginsExpanded.length = 0;
  1224. trustedOriginsExpanded.push(domain);
  1225. break;
  1226. }
  1227. trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]);
  1228. }
  1229. }
  1230. }
  1231. if (trustedOriginsExpanded.length) {
  1232. str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(","));
  1233. }
  1234. if (options.forceEnhancedClipboard === true) {
  1235. str += (str ? "&" : "") + "forceEnhancedClipboard=true";
  1236. }
  1237. if (typeof options.swfObjectId === "string" && options.swfObjectId) {
  1238. str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId);
  1239. }
  1240. return str;
  1241. };
  1242. /**
  1243. * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or
  1244. * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/").
  1245. *
  1246. * @returns the domain
  1247. * @private
  1248. */
  1249. var _extractDomain = function(originOrUrl) {
  1250. if (originOrUrl == null || originOrUrl === "") {
  1251. return null;
  1252. }
  1253. originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, "");
  1254. if (originOrUrl === "") {
  1255. return null;
  1256. }
  1257. var protocolIndex = originOrUrl.indexOf("//");
  1258. originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2);
  1259. var pathIndex = originOrUrl.indexOf("/");
  1260. originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex);
  1261. if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") {
  1262. return null;
  1263. }
  1264. return originOrUrl || null;
  1265. };
  1266. /**
  1267. * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`.
  1268. *
  1269. * @returns The appropriate script access level.
  1270. * @private
  1271. */
  1272. var _determineScriptAccess = function() {
  1273. var _extractAllDomains = function(origins) {
  1274. var i, len, tmp, resultsArray = [];
  1275. if (typeof origins === "string") {
  1276. origins = [ origins ];
  1277. }
  1278. if (!(typeof origins === "object" && origins && typeof origins.length === "number")) {
  1279. return resultsArray;
  1280. }
  1281. for (i = 0, len = origins.length; i < len; i++) {
  1282. if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) {
  1283. if (tmp === "*") {
  1284. resultsArray.length = 0;
  1285. resultsArray.push("*");
  1286. break;
  1287. }
  1288. if (resultsArray.indexOf(tmp) === -1) {
  1289. resultsArray.push(tmp);
  1290. }
  1291. }
  1292. }
  1293. return resultsArray;
  1294. };
  1295. return function(currentDomain, configOptions) {
  1296. var swfDomain = _extractDomain(configOptions.swfPath);
  1297. if (swfDomain === null) {
  1298. swfDomain = currentDomain;
  1299. }
  1300. var trustedDomains = _extractAllDomains(configOptions.trustedDomains);
  1301. var len = trustedDomains.length;
  1302. if (len > 0) {
  1303. if (len === 1 && trustedDomains[0] === "*") {
  1304. return "always";
  1305. }
  1306. if (trustedDomains.indexOf(currentDomain) !== -1) {
  1307. if (len === 1 && currentDomain === swfDomain) {
  1308. return "sameDomain";
  1309. }
  1310. return "always";
  1311. }
  1312. }
  1313. return "never";
  1314. };
  1315. }();
  1316. /**
  1317. * Get the currently active/focused DOM element.
  1318. *
  1319. * @returns the currently active/focused element, or `null`
  1320. * @private
  1321. */
  1322. var _safeActiveElement = function() {
  1323. try {
  1324. return _document.activeElement;
  1325. } catch (err) {
  1326. return null;
  1327. }
  1328. };
  1329. /**
  1330. * Add a class to an element, if it doesn't already have it.
  1331. *
  1332. * @returns The element, with its new class added.
  1333. * @private
  1334. */
  1335. var _addClass = function(element, value) {
  1336. if (!element || element.nodeType !== 1) {
  1337. return element;
  1338. }
  1339. if (element.classList) {
  1340. if (!element.classList.contains(value)) {
  1341. element.classList.add(value);
  1342. }
  1343. return element;
  1344. }
  1345. if (value && typeof value === "string") {
  1346. var classNames = (value || "").split(/\s+/);
  1347. if (element.nodeType === 1) {
  1348. if (!element.className) {
  1349. element.className = value;
  1350. } else {
  1351. var className = " " + element.className + " ", setClass = element.className;
  1352. for (var c = 0, cl = classNames.length; c < cl; c++) {
  1353. if (className.indexOf(" " + classNames[c] + " ") < 0) {
  1354. setClass += " " + classNames[c];
  1355. }
  1356. }
  1357. element.className = setClass.replace(/^\s+|\s+$/g, "");
  1358. }
  1359. }
  1360. }
  1361. return element;
  1362. };
  1363. /**
  1364. * Remove a class from an element, if it has it.
  1365. *
  1366. * @returns The element, with its class removed.
  1367. * @private
  1368. */
  1369. var _removeClass = function(element, value) {
  1370. if (!element || element.nodeType !== 1) {
  1371. return element;
  1372. }
  1373. if (element.classList) {
  1374. if (element.classList.contains(value)) {
  1375. element.classList.remove(value);
  1376. }
  1377. return element;
  1378. }
  1379. if (typeof value === "string" && value) {
  1380. var classNames = value.split(/\s+/);
  1381. if (element.nodeType === 1 && element.className) {
  1382. var className = (" " + element.className + " ").replace(/[\n\t]/g, " ");
  1383. for (var c = 0, cl = classNames.length; c < cl; c++) {
  1384. className = className.replace(" " + classNames[c] + " ", " ");
  1385. }
  1386. element.className = className.replace(/^\s+|\s+$/g, "");
  1387. }
  1388. }
  1389. return element;
  1390. };
  1391. /**
  1392. * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`,
  1393. * then we assume that it should be a hand ("pointer") cursor if the element
  1394. * is an anchor element ("a" tag).
  1395. *
  1396. * @returns The computed style property.
  1397. * @private
  1398. */
  1399. var _getStyle = function(el, prop) {
  1400. var value = _window.getComputedStyle(el, null).getPropertyValue(prop);
  1401. if (prop === "cursor") {
  1402. if (!value || value === "auto") {
  1403. if (el.nodeName === "A") {
  1404. return "pointer";
  1405. }
  1406. }
  1407. }
  1408. return value;
  1409. };
  1410. /**
  1411. * Get the zoom factor of the browser. Always returns `1.0`, except at
  1412. * non-default zoom levels in IE<8 and some older versions of WebKit.
  1413. *
  1414. * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`).
  1415. * @private
  1416. */
  1417. var _getZoomFactor = function() {
  1418. var rect, physicalWidth, logicalWidth, zoomFactor = 1;
  1419. if (typeof _document.body.getBoundingClientRect === "function") {
  1420. rect = _document.body.getBoundingClientRect();
  1421. physicalWidth = rect.right - rect.left;
  1422. logicalWidth = _document.body.offsetWidth;
  1423. zoomFactor = _round(physicalWidth / logicalWidth * 100) / 100;
  1424. }
  1425. return zoomFactor;
  1426. };
  1427. /**
  1428. * Get the DOM positioning info of an element.
  1429. *
  1430. * @returns Object containing the element's position, width, and height.
  1431. * @private
  1432. */
  1433. var _getDOMObjectPosition = function(obj) {
  1434. var info = {
  1435. left: 0,
  1436. top: 0,
  1437. width: 0,
  1438. height: 0
  1439. };
  1440. if (obj.getBoundingClientRect) {
  1441. var rect = obj.getBoundingClientRect();
  1442. var pageXOffset, pageYOffset, zoomFactor;
  1443. if ("pageXOffset" in _window && "pageYOffset" in _window) {
  1444. pageXOffset = _window.pageXOffset;
  1445. pageYOffset = _window.pageYOffset;
  1446. } else {
  1447. zoomFactor = _getZoomFactor();
  1448. pageXOffset = _round(_document.documentElement.scrollLeft / zoomFactor);
  1449. pageYOffset = _round(_document.documentElement.scrollTop / zoomFactor);
  1450. }
  1451. var leftBorderWidth = _document.documentElement.clientLeft || 0;
  1452. var topBorderWidth = _document.documentElement.clientTop || 0;
  1453. info.left = rect.left + pageXOffset - leftBorderWidth;
  1454. info.top = rect.top + pageYOffset - topBorderWidth;
  1455. info.width = "width" in rect ? rect.width : rect.right - rect.left;
  1456. info.height = "height" in rect ? rect.height : rect.bottom - rect.top;
  1457. }
  1458. return info;
  1459. };
  1460. /**
  1461. * Reposition the Flash object to cover the currently activated element.
  1462. *
  1463. * @returns `undefined`
  1464. * @private
  1465. */
  1466. var _reposition = function() {
  1467. var htmlBridge;
  1468. if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) {
  1469. var pos = _getDOMObjectPosition(_currentElement);
  1470. _extend(htmlBridge.style, {
  1471. width: pos.width + "px",
  1472. height: pos.height + "px",
  1473. top: pos.top + "px",
  1474. left: pos.left + "px",
  1475. zIndex: "" + _getSafeZIndex(_globalConfig.zIndex)
  1476. });
  1477. }
  1478. };
  1479. /**
  1480. * Sends a signal to the Flash object to display the hand cursor if `true`.
  1481. *
  1482. * @returns `undefined`
  1483. * @private
  1484. */
  1485. var _setHandCursor = function(enabled) {
  1486. if (_flashState.ready === true) {
  1487. if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") {
  1488. _flashState.bridge.setHandCursor(enabled);
  1489. } else {
  1490. _flashState.ready = false;
  1491. }
  1492. }
  1493. };
  1494. /**
  1495. * Get a safe value for `zIndex`
  1496. *
  1497. * @returns an integer, or "auto"
  1498. * @private
  1499. */
  1500. var _getSafeZIndex = function(val) {
  1501. if (/^(?:auto|inherit)$/.test(val)) {
  1502. return val;
  1503. }
  1504. var zIndex;
  1505. if (typeof val === "number" && !_isNaN(val)) {
  1506. zIndex = val;
  1507. } else if (typeof val === "string") {
  1508. zIndex = _getSafeZIndex(_parseInt(val, 10));
  1509. }
  1510. return typeof zIndex === "number" ? zIndex : "auto";
  1511. };
  1512. /**
  1513. * Detect the Flash Player status, version, and plugin type.
  1514. *
  1515. * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code}
  1516. * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript}
  1517. *
  1518. * @returns `undefined`
  1519. * @private
  1520. */
  1521. var _detectFlashSupport = function(ActiveXObject) {
  1522. var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = "";
  1523. /**
  1524. * Derived from Apple's suggested sniffer.
  1525. * @param {String} desc e.g. "Shockwave Flash 7.0 r61"
  1526. * @returns {String} "7.0.61"
  1527. * @private
  1528. */
  1529. function parseFlashVersion(desc) {
  1530. var matches = desc.match(/[\d]+/g);
  1531. matches.length = 3;
  1532. return matches.join(".");
  1533. }
  1534. function isPepperFlash(flashPlayer