Repository: vincepare/iframeTracker-jquery Branch: master Commit: 492d10878b57 Files: 20 Total size: 42.2 KB Directory structure: gitextract_k98m94vz/ ├── .eslintrc ├── .gitignore ├── .npmignore ├── .travis.yml ├── CONTRIBUTING.md ├── Gruntfile.js ├── LICENSE.txt ├── README.md ├── bower.json ├── demo/ │ ├── index.html │ └── sample-iframe/ │ ├── blue.html │ └── red.html ├── package.json ├── src/ │ ├── jquery.iframetracker.js │ └── umd.hbs └── test/ └── unit/ ├── .eslintrc ├── iframeTracker-jQuery1.html ├── iframeTracker-jQuery2.html ├── iframeTracker-jQuery3.html └── iframeTracker_test.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .eslintrc ================================================ { "root": true, "extends": "jquery", "globals": { "window": true, "jQuery": true, "define": true, "module": true, "noGlobal": true, "document": true, "navigator": true, "console": true }, "rules": { "space-in-parens": "off", "quotes": [ "warn", "double", { "avoidEscape": true } ], "computed-property-spacing": ["error", "never"], "max-len": [ "warn", { "code": 100, "ignoreComments": true, "ignoreUrls": true, "ignoreRegExpLiterals": true, "ignoreStrings": true } ], "lines-around-comment": [ "error", { "beforeLineComment": true, "allowBlockStart": true, "allowObjectStart": true } ], "no-unused-vars": [ "error", { "args": "none" } ], "array-bracket-spacing": [ "error", "never" ], "strict": "off" } } ================================================ FILE: .gitignore ================================================ *.diff *.patch .DS_Store /node_modules /dist ================================================ FILE: .npmignore ================================================ /demo /bower.json /Gruntfile.js /.eslintrc /.travis.yml /test ================================================ FILE: .travis.yml ================================================ language: node_js sudo: false node_js: - "node" cache: directories: - node_modules ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing to iframeTracker ## Bug report * Please provide a live example (use tools like [jsbin](https://jsbin.com), [jsfiddle](https://jsfiddle.net) or [codepen](https://codepen.io/)) * Indicate which browsers the issue can be reproduced in ## Build setup 1. Fork and clone the repository 1. Run `npm install` to install all dependencies 1. Run `npm test` to check your build environment ## Coding guidelines * Enforce existing coding style (*eslint* will help you : `npx grunt eslint`) * Use UTF-8 charset * Beware to not decrease code coverage (write new tests for new code) ## Pull request 1. Create a new branch from `develop` (please don't work on your `develop` branch directly) 1. Run `npm test` 1. Open `test/unit/*.html` unit test files in actual browser to ensure tests pass everywhere 1. Update the documentation to reflect any changes 1. Push to your fork and submit a pull request ================================================ FILE: Gruntfile.js ================================================ "use strict"; module.exports = function(grunt) { grunt.util.linefeed = "\n"; grunt.initConfig({ pkg: grunt.file.readJSON("package.json"), banner: "/*! <%= pkg.name %> v<%= pkg.version %>" + "<%= pkg.homepage ? ' | ' + pkg.homepage : '' %>" + " | Copyright (c) 2013-<%= grunt.template.today('yyyy') %> <%= pkg.author %>" + " | Licensed <%= pkg.license %> */", copy: { options: { process: function(content, srcpath) { return grunt.template.process(content); } }, main: { src: "src/jquery.iframetracker.js", dest: "dist/jquery.iframetracker.js" } }, umd: { all: { src: "dist/jquery.iframetracker.js", template: "./src/umd.hbs", deps: { "default": ["jQuery"], amd: ["jquery"], cjs: ["jquery"] } } }, uglify: { options: { banner: "<%= banner %>" }, main: { src: ["dist/jquery.iframetracker.js"], dest: "dist/jquery.iframetracker.min.js" } }, eslint: { target: ["src/**/*.js", "test/**/*.js", "Gruntfile.js"] }, qunit: { files: ["test/**/*.html"] } }); grunt.loadNpmTasks("grunt-contrib-copy"); grunt.loadNpmTasks("grunt-contrib-uglify"); grunt.loadNpmTasks("grunt-eslint"); grunt.loadNpmTasks("grunt-contrib-qunit"); grunt.loadNpmTasks("grunt-umd"); grunt.registerTask("compile", ["copy", "umd", "uglify"]); grunt.registerTask("default", ["eslint", "qunit", "compile"]); }; ================================================ FILE: LICENSE.txt ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2013 Vincent Paré Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ iframeTracker jQuery Plugin =========================== iframeTracker is a jQuery plugin that allow to track clicks on iframes. This is very useful to : - track clicks on Google Adsense (google uses iframes to display ads) - track clicks on Facebook Like buttons - track clicks on Youtube embed video player - ... and any other iframe ! Try it now : [demo](https://cdn.rawgit.com/vincepare/iframeTracker-jquery/master/demo/index.html). How does it work ? ------------------ Since it's impossible to read iframe content (DOM) from the parent page due to the [same origin policy](http://en.wikipedia.org/wiki/Same-origin_policy), tracking is based on the blur event associated to a **page/iframe boundary monitoring system** telling over which iframe is the mouse cursor at any time. How to use ? ------------ Match the iframe elements you want to track with a jQuery selector and call `iframeTracker` with a callback function that will be called when a click on the iframe is detected : ```javascript jQuery(document).ready(function($){ $('.iframe_wrap iframe').iframeTracker({ blurCallback: function(event) { // Do something when the iframe is clicked (like firing an XHR request) } }); }); ``` You can also just pass a function, that will be then registered as the `blurCallback` : ```javascript jQuery(document).ready(function($){ $('.iframe_wrap iframe').iframeTracker(function(event) { // Do something when the iframe is clicked (like firing an XHR request) }); }); ``` ### Advanced tracking ```javascript jQuery(document).ready(function($){ $('.iframe_wrap iframe').iframeTracker({ blurCallback: function(event) { // Do something when iframe is clicked (like firing an XHR request) // You can know which iframe element is clicked via this._overId }, overCallback: function(element, event) { this._overId = $(element).parents('.iframe_wrap').attr('id'); // Saving the iframe wrapper id }, outCallback: function(element, event) { this._overId = null; // Reset hover iframe wrapper id }, _overId: null }); }); ``` #### Cancel tracking You can remove a tracker attached to an iframe by calling `.iframeTracker()` with either `false` or `null` : ```javascript $('#iframe_red_1 iframe').iframeTracker(false); $('#iframe_red_2 iframe').iframeTracker(null); ``` Full tutorial available [here](http://www.finalclap.com/tuto/track-iframe-click-jquery-87/) (it's in French). Tested on jQuery `1.4.4` to `1.11.0`, `2.1.4` & `3.2.1`. ---------- ### Install With npm : ```bash npm install jquery.iframetracker ``` With bower : ```bash bower install jquery.iframetracker ``` ### About mobile devices This plugin doesn't work on mobile devices such as smartphones and tablets, because this hardware uses a touchscreen instead of a mouse as click input. This design makes the boundary monitoring trick ineffective. ### Donate Donations are welcome :) via [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=YXDJFGF8GCGLA&item_name=Vincent%20Par%e9%20-%20www.finalclap.com&item_number=iframeTracker%2dgithub¤cy_code=EUR&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted), [Flattr](https://flattr.com/submit/auto?user_id=finalclap&url=https://github.com/vincepare/iframeTracker-jquery&title=iframeTracker%20jQuery%20Plugin&language=&tags=github&category=software) or Bitcoin at this address : `3G5uTti2JPAT738uDeQXjrN7tUj2NZjt6M` or by flashing this lovely QR code :  ================================================ FILE: bower.json ================================================ { "name": "jquery.iframetracker", "version": "2.1.0", "homepage": "https://github.com/vincepare/iframeTracker-jquery", "authors": [ "Vincent Paré" ], "description": "jQuery Plugin to track click on iframes (like Google Adsense or Facebook Like button).", "main": "dist/jquery.iframetracker.js", "moduleType": [ "globals" ], "keywords": [ "iframe", "youtube", "adsense", "advertising", "click" ], "license": "Apache-2.0", "ignore": [ "**/.*", "node_modules", "bower_components", "test", "tests", "demo", "src", "Gruntfile.js", "README.md", "package-lock.json", "package.json" ], "dependencies": { "jquery": ">=1.4.4" } } ================================================ FILE: demo/index.html ================================================
Read the tutorial on how the tracking works at http://www.finalclap.com/tuto/track-iframe-click-jquery-87/ (it's in French).
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.
#header h1 a {
display: block;
width: 300px;
height: 80px;
}
Remove tracking
© Vincent Paré, using jQuery & Bootstrap from twitter
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante.
Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.
================================================ FILE: package.json ================================================ { "name": "jquery.iframetracker", "version": "2.1.0", "description": "jQuery Plugin to track click on iframes (like Google Adsense or Facebook Like button).", "main": "dist/jquery.iframetracker.js", "repository": { "type": "git", "url": "https://github.com/vincepare/iframeTracker-jquery.git" }, "keywords": [ "jquery-plugin", "iframe", "youtube", "adsense", "advertising", "click" ], "author": "Vincent Paré", "license": "Apache-2.0", "bugs": { "url": "https://github.com/vincepare/iframeTracker-jquery/issues" }, "homepage": "https://github.com/vincepare/iframeTracker-jquery", "scripts": { "test": "grunt eslint qunit", "build": "grunt", "prepare": "grunt" }, "peerDependencies": { "jquery": ">=1.4.4" }, "devDependencies": { "eslint-config-jquery": "^1.0.1", "grunt": "^1.0.1", "grunt-contrib-copy": "^1.0.0", "grunt-contrib-qunit": "^2.0.0", "grunt-contrib-uglify": "^3.0.1", "grunt-eslint": "^19.0.0", "grunt-umd": "^2.4.0" } } ================================================ FILE: src/jquery.iframetracker.js ================================================ /*! * jQuery iframe click tracking plugin * * @author Vincent Paré * @copyright © 2013-<%= grunt.template.today("yyyy") %> Vincent Paré * @license http://opensource.org/licenses/Apache-2.0 * @version <%= pkg.version %> */ (function($) { // Tracking handler manager $.fn.iframeTracker = function(handler) { // Building handler object from handler function if (typeof handler == "function") { handler = { blurCallback: handler }; } var target = this.get(); if (handler === null || handler === false) { $.iframeTracker.untrack(target); } else if (typeof handler == "object") { $.iframeTracker.track(target, handler); } else { throw new Error("Wrong handler type (must be an object, or null|false to untrack)"); } return this; }; // Iframe tracker common object $.iframeTracker = { // State focusRetriever: null, // Element used for restoring focus on window (element) focusRetrieved: false, // Says if the focus was retrieved on the current page (bool) handlersList: [], // Store a list of every trakers (created by calling $(selector).iframeTracker...) isIE8AndOlder: false, // true for Internet Explorer 8 and older // Init (called once on document ready) init: function() { // Determine browser version (IE8-) ($.browser.msie is deprecated since jQuery 1.9) try { if ($.browser.msie === true && $.browser.version < 9) { this.isIE8AndOlder = true; } } catch (ex) { try { var matches = navigator.userAgent.match(/(msie) ([\w.]+)/i); if (matches[2] < 9) { this.isIE8AndOlder = true; } } catch (ex2) {} } // Listening window blur $(window).focus(); $(window).blur(function(e) { $.iframeTracker.windowLoseFocus(e); }); // Focus retriever (get the focus back to the page, on mouse move) $("body").append(''); this.focusRetriever = $("#focus_retriever"); this.focusRetrieved = false; // Special processing to make it work with my old friend IE8 (and older) ;) if (this.isIE8AndOlder) { // Blur doesn't works correctly on IE8-, so we need to trigger it manually this.focusRetriever.blur(function(e) { e.stopPropagation(); e.preventDefault(); $.iframeTracker.windowLoseFocus(e); }); // Keep focus on window (fix bug IE8-, focusable elements) $("body").click(function(e) { $(window).focus(); }); $("form").click(function(e) { e.stopPropagation(); }); // Same thing for "post-DOMready" created forms (issue #6) try { $("body").on("click", "form", function(e) { e.stopPropagation(); }); } catch (ex) { console.log("[iframeTracker] Please update jQuery to 1.7 or newer. (exception: " + ex.message + ")"); } } }, // Add tracker to target using handler (bind boundary listener + register handler) // target: Array of target elements (native DOM elements) // handler: User handler object track: function(target, handler) { // Adding target elements references into handler handler.target = target; // Storing the new handler into handler list $.iframeTracker.handlersList.push(handler); // Binding boundary listener $(target) .bind("mouseover", { handler: handler }, $.iframeTracker.mouseoverListener) .bind("mouseout", { handler: handler }, $.iframeTracker.mouseoutListener); }, // Remove tracking on target elements // target: Array of target elements (native DOM elements) untrack: function(target) { if (typeof Array.prototype.filter != "function") { console.log("Your browser doesn't support Array filter, untrack disabled"); return; } // Unbinding boundary listener $(target).each(function(index) { $(this) .unbind("mouseover", $.iframeTracker.mouseoverListener) .unbind("mouseout", $.iframeTracker.mouseoutListener); }); // Handler garbage collector var nullFilter = function(value) { return value === null ? false : true; }; for (var i in this.handlersList) { // Prune target for (var j in this.handlersList[i].target) { if ($.inArray(this.handlersList[i].target[j], target) !== -1) { this.handlersList[i].target[j] = null; } } this.handlersList[i].target = this.handlersList[i].target.filter(nullFilter); // Delete handler if unused if (this.handlersList[i].target.length === 0) { this.handlersList[i] = null; } } this.handlersList = this.handlersList.filter(nullFilter); }, // Target mouseover event listener mouseoverListener: function(e) { e.data.handler.over = true; $.iframeTracker.retrieveFocus(); try { e.data.handler.overCallback(this, e); } catch (ex) {} }, // Target mouseout event listener mouseoutListener: function(e) { e.data.handler.over = false; $.iframeTracker.retrieveFocus(); try { e.data.handler.outCallback(this, e); } catch (ex) {} }, // Give back focus from an iframe to parent page retrieveFocus: function() { if (document.activeElement && document.activeElement.tagName === "IFRAME") { $.iframeTracker.focusRetriever.focus(); $.iframeTracker.focusRetrieved = true; } }, // Calls blurCallback for every handler with over=true on window blur windowLoseFocus: function(e) { for (var i in this.handlersList) { if (this.handlersList[i].over === true) { try { this.handlersList[i].blurCallback(e); } catch (ex) {} } } } }; // Init the iframeTracker on document ready $(document).ready(function() { $.iframeTracker.init(); }); })(jQuery); ================================================ FILE: src/umd.hbs ================================================ (function (root, factory) { if (typeof define === 'function' && define.amd) { define({{#if amdModuleId}}'{{amdModuleId}}', {{/if}}[{{{amdDependencies.wrapped}}}], function ({{{amdDependencies.params}}}) { return ({{#if objectToExport}}root['{{{objectToExport}}}'] = {{/if}}factory({{{amdDependencies.params}}})); }); } else if (typeof module === 'object' && module.exports) { module.exports = factory({{{cjsDependencies.wrapped}}}); } else { {{#if globalAlias}}root['{{{globalAlias}}}'] = {{else}}{{#if objectToExport}}root['{{{objectToExport}}}'] = {{/if}}{{/if}}factory({{{globalDependencies.normal}}}); } }(this, function ({{dependencies}}) { {{{code}}} {{#if objectToExport}} return {{{objectToExport}}}; {{/if}} })); ================================================ FILE: test/unit/.eslintrc ================================================ { "globals": { "QUnit": true } } ================================================ FILE: test/unit/iframeTracker-jQuery1.html ================================================