Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts

Sunday, August 28, 2016

Writing a Chrome Extension - My First Attempt

I decided that I want to learn how to write an Extension for Chrome that will hopefully block those annoying modal dialogs. There are plenty of popup blockers that block the "traditional" new window, but this is trickier.

What is a modal dialog and how do they work?


A modal dialog or modal popup is nothing more than a chunk of HTML that starts out as "hidden", but then is shown - usually when it's visible, access to the page is disabled. Many times, the page is grayed out. The end result is that the user has to take some action to close the dialog, at a minimum, the user needs to click a close button. Sometimes the user will need to sign up for something. Whatever, it's annoying.

My Extension


So, I (we) are going to learn, from scratch, how to create a plugin. My design is sketchy right now, but I'm envisioning that the extension will:

  1. When a user is presented with a modal dialog, (s)he can activate the plugin, click on the popup and add it to a list.
  2. The extension will save the page URL and the web component that is the offending popup. 
  3. The app will save this information to localStorage
  4. Next time the user navigates to a saved URL, the app will find the component and (what should I do, delete it? I could set up a MutationObserver which will listen for the element's change in hidden status and change it to hidden again before it can show itself. ).
  5. I *could* also create an option to disable all iframes.
  6. I could also implement some pre-existing blockers for popular sites that have popups, for example, Youtube.  
My thoughts on this design: 
  1. This extension will only "remember" settings for each browser. I could maybe (in V2) add an export/import feature.
  2. User must have localStorage enabled. 
  3. A concern with localStorage is DOM blocking because the API is synchronous. I'm not worried about this because the write operation is done when the user clicks off of a page. The read is a little trickier. I could read the data into memory asynchronously, but seriously, we are talking about, at most, 3 items per page.

Let's Start!


Since this is a relatively simple project, you can use pretty much any text editor, well except for the icon. I'm using VS Code from Microsoft. It's free and lightweight. It understands HTML, Javascript, JSON, etc. 

I created a branch in GitHub for this step. Mustering all my creativity, I decided to call this branch "Step-1".  Go ahead and download it now.

Here are a few things about extensions:
  1. The icon must be a PNG. 
  2. The manifest_version must be 2.
  3. You cannot use CDNs to reference tools like jQuery. You need to download a copy.
  4. No JavaScript can exist in an html file. (This is good practice anyway.)
manifest.json file:
1:  {  
2:   "manifest_version": 2,  
3:   "name": "Rich Modal Dialog Blocker",  
4:   "version": "0.1.0",  
5:   "description": "Rich Modal Dialog Blocker",  
6:   "browser_action": {  
7:    "default_icon" : "rmb.png",  
8:    "default_popup": "main.html"  
9:   },  
10:   "permissions": [  
11:      "tabs",  
12:      "notifications",  
13:      "http://*/",  
14:      "https://*/"  
15:    ]  
16:  }  

To create an extension, open Chrome and navigate to chrome://extensions/. Or click the top right menu | more tools | extensions. Check the checkbox that says Developer Mode. This lets you upload extension code from your machine.  Click the "Lost Unpacked Extension" button, navigate to your folder where the manifest.json exists and OK. If the planets aligned, then you should see a new extension. Look in the upper right of the browser and you should see my beautiful icon. (OK, I'm really not an artist.)

This is a Hello, World level project at this point. Very simple. While it's certainly not required, I included jquery2.2.4.js because I really like how jQuery makes JavaScript simpler. Right now, we have 5 code files and a README.md.

The manifest is straightforward right now.  Main.html (noted in the browser_action | default_popup item) is the popup page we see when we click on the extension's icon. The content.js file just has some simple test code. Right now, all it does is change the inner html of the h2#heading element to "After click". 

If you decide to make some modifications to test it, hit ctrl-r after saving and the extension will refresh. There's also a little Reload (ctrl-r) link on the extension page. It's a wonderful world when we have choices!

If you want to play with this a bit, go ahead. Otherwise, let's do something more interesting - let's modify the html of an active page. Stand by for Part 2.












Saturday, June 28, 2014

Extending jQuery Selectors

A small source of frustration for jQuery developers is the :contains() selector doesn't have a startswith option. A selector indicating elements that start with a string is extremely helpful, but the good folks at jQuery central haven't given us one.

Good news!  We can easily write one ourselves.

$.extend($.expr[":"], {
    "startswith": function(elem, i, data, set) {
        var txt = $.trim($(elem).text());
        var term = data[3];
        return txt.indexOf(term) === 0;
    }
}); 
Simply place this into a convenient location (after your jQuery script) and you'll be able to use ":startswith"

For example: to find all the
s that have "blah" as their inner text, just do this:

    $('div:startswith("blah")')...

Here's a jsfiddle to use as a quick demo: http://jsfiddle.net/richbuff/43AtR/

Hope this helps! 

Tuesday, July 24, 2012

Cross Domain AJAX Calls with PhoneGap and jQuery

When creating a PhoneGap app, you are essentially creating a web page and it lives in the 'localhost' domain. Unfortunately, by default AJAX calls are only supported in the same domain - unless you use JSONP (JSON with padding). You can read more about JSONP here: http://en.wikipedia.org/wiki/JSONP

Create the Mobile Web Page

Ok, let's cheat... well, is saving time cheating?  I went to http://jquerymobile.com/ and used the prototyping tool and built a quick HTML5 page.
















When I was finished, I clicked the "Download HTML" button and was given a neat little zip file with a web page, a CSS file and a JS file. I renamed the CSS and JS files to demo.* and copied them into my PhoneGap www\include folder.

I dropped the HTML page into the www folder and opened it in the editor.  I modified the HTML file to reference the newly added CSS and JS. I renamed the HTML file to ajaxdemo.html.  I also had to update the main java file of the PhoneGap app.

public void onCreate(Bundle savedInstanceState)  
   {  
     super.onCreate(savedInstanceState);  
     //setContentView(R.layout.main);  
     super.loadUrl("file:///android_asset/www/ajaxdemo.html");  
   }  

For a quick test, I viewed the HTML file in a browser to make sure it looks OK.  I could, at this point, compile and run the app in my phone.

Add a PHP Page to Call With AJAX

This is a very simple PHP page.  All we want to do is take some parameters from the Request and return a JSON object wrapped in a JSONP function.  You'll see what I mean when you read the code. I call this name.php.

firstname = $_GET['first'];  
 $theName->lastname = $_GET['last'];
  
 echo $_GET['callback'] .'('. json_encode($theName) . ')';  
 ?>  

The first lines simply grab the request values from the GET collection and assign it to a dynamically created object. PHP is like JavaScript in that you can create an object's members on the fly.

The JSONP part of this return is the
echo $_GET['callback'] .'('. json_encode($theName) . ')'
part.  When we create the actual AJAX request, we will declare a function in which to wrap our JSON response. This is part of our GET request. You'll see more when we build the AJAX request.

The PHP function json_encode()  is handy for taking your object or collection and turning it into a JSON object. You can find more info here.

I uploaded this file to my hosting account, so I can call it from my local code. After uploading, I can simulate the AJAX call with the following URL:
http://mysite.com/name.php?callback=jp&first=pat&last=buff

If you've copied my code correctly, you should see results that look like:
jp({"firstname":"pat","lastname":"buff"})

Now For AJAX and other JavaScript

The server-side code is in place.  Let's add the JavaScript.
    function appReady(){  
       $("#infodiv").html("Testing JSONP with jQuery");  
     }  
   
     $(document).ready(function(){  
       $("#get-name").click(function(){  
         handleClick();  
       });  
   
       $("#ajax_error").ajaxError(function(e, jqxhr, settings, exception) {  
         $(this).text( "Error requesting page " + settings.url);  
       });  
     });  
   
     document.addEventListener("deviceready", appReady, false);  
   
     $( document ).bind( "mobileinit", function() {  
       // Make your jQuery Mobile framework configuration changes here!  
       $("#infodiv").html('mobileinit worked');  
       $.mobile.allowCrossDomainPages = true;  
     });  
   
     function handleClick(){  
       var url = 'http://fineglasswork.com/histmarkers/client/partial.php';  
   
       $.ajax({  
         type: 'GET',  
         url: url,  
         contentType: "application/json",  
         dataType: 'jsonp',  
         data: {first: $("#firstname").val(), last: $("#lastname").val() },  
         crossDomain: true,  
         success: function(res) {  
           $("#resultsdiv").html("Hello, " + res.firstname + " " + res.lastname);  
           console.dir(res.fullname);  
         },  
         error: function(e) {  
           console.log(e.message);  
         },  
         complete: function(data) {  
           console.log(e.message);  
         }  
       });  
   
     }  

The guts of this script - the part we want to focus on - is the handleClick() function.  This is where we make our AJAX call with jQuery. We should pay special attention to these parameters:

         contentType: "application/json",  
         dataType: 'jsonp',  
         data: {first: $("#firstname").val(), last: $("#lastname").val() },  
         crossDomain: true,  

Declaring the dataType as 'jsonp' will automatically add the 'callback' parameter to the GET request. crossDomain is set to true (of course! otherwise we wouldn't need to use JSONP). The data is passed as a JSON object.  The data elements will automatically be added to the GET request for us - no need to build a URL with a querystring.

We are ready to run our code!  I usually use my HTC Evo, but in this case, I ran it with an emulator so I could get this beautiful screen shot.  I entered a first name and last into the Text fields and clicked the "Click Me" button to get this result.













Now isn't that just gorgeous!

Something you might notice is that the heading is different when you see the page in your browser.  That's because we modify that header in the appReady handler.  The appReady handler is defined in this line:
    document.addEventListener("deviceready", appReady, false);  
The deviceready event is used to notify the app that PhoneGap is loaded.  When writing PhoneGap apps, you should wait until deviceready event is called before depending on any PhoneGap functionality to be available.

That's it for now!  I hope this was helpful.  Please feel free to ask questions or suggest changes.

Edit: I've uploaded the code in this Post to GitHub. https://github.com/RichBuff/PhoneGap-App-with-JSONP-AJAX-Call


You can also find this article on my new blog site: http://alpheussoftware.com/?p=20