www.webdeveloper.com
Results 1 to 12 of 12

Thread: Need a bit of help with javascript

  1. #1
    Join Date
    May 2014
    Posts
    5

    Need a bit of help with javascript

    I'm working on a side project to help me learn javascript, and seem to be having a bit of trouble getting the code to do what I want.

    What I'm doing: I'm making a chrome extension that reads in the tab url and returns an image based on the ascii of that url

    Code:
    var urlPath;
    var URLNum;
    var num;
    
    var something = {
    
        grabURL: function() {
            // grab the url of current tab using Chrome API 'chrome.tabs.query'
            chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabArray) {
                var tab = tabArray[0];
                urlPath = tab;
            });
        },
    	
        generateNum_: function() {
            var path = grabTabURL();
    		
            for(var i = 0; i < path.length; i++) {
                URLNum += path.charCodeAt(i);
            }
    		
            return URLNum;
        },
    	
        generateSomething_: function() {
            num = generateNum_();
            var c = new Class(); // mostly abstract right now and doesn't really do anything - will probably move the generate image into these class/sub classes
    		
            if(num >= 0 && num < 800) {
                //a = new ChildClassA();
                var img = document.createElement("img");
                img.src = "img/imageA.gif";
                document.body.appendChild(img);
            } else if(num >= 300 && num < 600) {
                b = new ChildClassB();
                // repeat the image generate part
            }
        }
    };
    
    
    // Run script as soon as the document's DOM is ready.
    document.addEventListener('DOMContentLoaded', function() {
      something.grabURL();
    });
    What's wrong with my code: The urlNum and num remains as undefined. Following what the code does, urlNum is suppose to use whatever urlPath is to generate a number. Which "num" then uses to determine what picture to show.

    urlPath does seem to return an object with a url in it (I checked the debugger) so I'm not really sure what's wrong.

    Can someone help me?

  2. #2
    Join Date
    Nov 2010
    Posts
    1,085
    where is the grabTabURL() function?

  3. #3
    Join Date
    May 2014
    Posts
    5
    sorry typo, it's actually the grabURL() function not grabTabURL().

  4. #4
    Join Date
    Nov 2010
    Posts
    1,085
    so maybe you should post your actual code because what you have posted has this line in it:
    Code:
    var path = grabTabURL();

  5. #5
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    943
    Perhaps I've missed something, but it almost seems like your problem is simply that you are never actually setting URLnum. When the document is ready you call grabURL(), which of course gets the tab URL, but that's all that's called. Minus your typo it's looking like you actually want to run the generateNum_() function of your something class. This would grab the URL and then set your URLnum variable.

    Also, as a side note, while I'm no expert with classes I do find it a bit odd you're using one to set global variables. And even more specifically your generateNum_() function returns the value of URLnum, which makes me feel like you shouldn't be using the same name for the global variable and the class variable.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  6. #6
    Join Date
    May 2014
    Posts
    5
    Quote Originally Posted by xelawho View Post
    so maybe you should post your actual code because what you have posted has this line in it:
    Code:
    var path = grabTabURL();
    Unfortunately I cannot edit the post yet... there is no option to do so

    Quote Originally Posted by Sup3rkirby View Post
    Perhaps I've missed something, but it almost seems like your problem is simply that you are never actually setting URLnum. When the document is ready you call grabURL(), which of course gets the tab URL, but that's all that's called. Minus your typo it's looking like you actually want to run the generateNum_() function of your something class. This would grab the URL and then set your URLnum variable.

    Also, as a side note, while I'm no expert with classes I do find it a bit odd you're using one to set global variables. And even more specifically your generateNum_() function returns the value of URLnum, which makes me feel like you shouldn't be using the same name for the global variable and the class variable.
    I was trying to do an OOP approach since that's what I'm familiar with (e.g java, c# etc). The function grabURL() returns the variable urlPath with the url in it. Then generateNum_() creates a local variable that stores the value that is returned in grabURL() and uses it to generate some random number and returns that number (which is then used in generateSomething_().

    In reference to the colored red part, do you suggest something like this:

    Code:
    grabURL: function() {
        ...
        var g = generateNum_(urlPath); // then remove the var path = grabURL() and so on
        // this would call generateNum_() once everything in grabURL finishes
        // I did this before, but got an error. I'll replicate it again and post the error
    }

  7. #7
    Join Date
    Mar 2005
    Location
    Behind you...
    Posts
    943
    I was thinking something much simpler:
    Code:
    document.addEventListener('DOMContentLoaded', function() {
      URLnum = something.generateNum_();
    });
    Logically that will call the generateNum_() function, which should get the URL and then return a URLnum value, which then gets set to URLnum (and thus my confusion with variable names). But frankly I don't really have a solid understanding of everything you're trying to achieve. For instance, you may want to set the variable num equal to this value instead. And since you're using the global variable names inside of the class then calling generateNum_() first should set your first two variables, and you could then of course set num equal to the return value.
    "Given billions of tries, could a spilled bottle of ink ever fall into the words of Shakespeare?"

  8. #8
    Join Date
    May 2014
    Posts
    5
    I should probably remove those global variables as they're not needed, and can be used as local variables.

    What I'm trying to do:
    - use the grabURL() to grab the active tab's url
    - use generateNum_() to convert that url into an ascii number value
    - finally, based on what the ascii value is, display an image using generateSomething_()

    I thought the addEventListener would simply go through the three functions one by one. But they don't. So I changed it to something like this:

    Code:
    document.addEventListener('DOMContentLoaded', function() {
      something.generateSomething(); // I changed it from private to public and made the others private
    });
    So doing it this way, logically it would call the generateNum_() which calls the grabURL_(). But when I debugged it, I get this error:

    Code:
    Uncaught ReferenceError: generateNum_ is not defined              popup.js:36
    chromeEmAllExt.generateSomething                                  popup.js:36
    (anonymous function)
    Full updated code

    Code:
    var something = {
    
        grabURL_: function() {
            var urlPath;
    
            // grab the url of current tab using Chrome API 'chrome.tabs.query'
            chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabArray) {
                var tab = tabArray[0];
                urlPath = tab;
            });
    
            return urlPath;
        },
    	
        generateNum_: function() {
            var path = grabURL_();
            var URLNum;
    		
            for(var i = 0; i < path.length; i++) {
                URLNum += path.charCodeAt(i);
            }
    		
            return URLNum;
        },
    	
        generateSomething: function() {
            var num = generateNum_();
            var c = new Class(); // mostly abstract right now and doesn't really do anything - will probably move the generate image into these class/sub classes
    		
            if(num >= 0 && num < 800) {
                //c = new ChildClassA();
                var img = document.createElement("img");
                img.src = "img/imageA.gif";
                document.body.appendChild(img);
    
            } else if(num >= 300 && num < 600) {
                //c = new ChildClassB();
                // repeat the image generate part
            }
        }
    };
    
    document.addEventListener('DOMContentLoaded', function() {
        something.generateSomething();
    });

  9. #9
    Join Date
    May 2014
    Posts
    9
    Quote Originally Posted by xelawho View Post
    where is the grabTabURL() function?
    It is the main function and it has disappear from it.

  10. #10
    Join Date
    May 2014
    Posts
    1,017
    Uhm... since you built "generateNum_" as a method of "something"... don't you have to say "this." -- as in:

    this.generateNum_();

    Not sure why you feel the need for that underscore. Also since all you're doing is a document.body.appendchild I'm not sure why you aren't just using an anonymous function before </body> in the markup (where external scripts load faster anyways)

    Your grabURL function doesn't even make sence, since it has a function inside it that is never called so it always returns an empty object.

    Also, your test for >300 or <600 will never run, since both numbers are between 0 and 800.

    Really I think you have a bunch of functions for nothing, and from what I'm seeing there's no reason to wait for contentloaded or onload -- just place the script right before </body> where the DOM is already built and complete.

    Code:
    (function() {
    
    	var
    		d = document,
    		path,
    		num = 0;
    
    	chrome.tabs.query(
    		{active: true, lastFocusedWindow: true},
    		function(tabArray) { path = tabArray[0]; }
    	);
    
    	for (var i = 0; i < path.length; i++) {
    		num += path.charCodeAt(i);
    	}
    
    	function makeImage(src) {
    		var img = d.createElement('img');
    		img.src = src;
    		d.body.appendchild(img);
    	}
    
    	if (num >= 300 && num < 600) {
    		makeImage('img/imageA.gif');
    	} else if (num >= 0 && num < 800) {
    		makeImage('img/imageB.gif');
    	}
    
    })();
    Though I'm guessing a bit here... Generating your seed from chrome.tabs, an extension only function that might not even return anything but gibberish is ... interesting. Seems a wee bit complex and I'd be surprised given how you're doing that 'num' value if it returned a value less than 800.... but I guess that would hinge on the length of the 'path' returned by that. Assuming ascii limits that would be... six character limit? Haven't had a chance to play with that one yet.
    Java is to JavaScript as Ham is to Hamburger.

  11. #11
    Join Date
    May 2014
    Posts
    5
    Quote Originally Posted by deathshadow View Post
    Uhm... since you built "generateNum_" as a method of "something"... don't you have to say "this." -- as in:

    this.generateNum_();

    Not sure why you feel the need for that underscore. Also since all you're doing is a document.body.appendchild I'm not sure why you aren't just using an anonymous function before </body> in the markup (where external scripts load faster anyways)

    Your grabURL function doesn't even make sence, since it has a function inside it that is never called so it always returns an empty object.

    Also, your test for >300 or <600 will never run, since both numbers are between 0 and 800.

    Really I think you have a bunch of functions for nothing, and from what I'm seeing there's no reason to wait for contentloaded or onload -- just place the script right before </body> where the DOM is already built and complete.

    Though I'm guessing a bit here... Generating your seed from chrome.tabs, an extension only function that might not even return anything but gibberish is ... interesting. Seems a wee bit complex and I'd be surprised given how you're doing that 'num' value if it returned a value less than 800.... but I guess that would hinge on the length of the 'path' returned by that. Assuming ascii limits that would be... six character limit? Haven't had a chance to play with that one yet.
    I read that you can't put inline scripts for an extension.

    The grabURL does return an object with the url (at least in the original code)... I haven't been able to check if it does in my updated code because I'm getting errors in it.

    The number range tests don't matter (that much) at this point. I'm just focusing on trying to get it to work and load an image. Once that's done, I'll get back to correcting the logic.

    As for the ascii, I'm getting the ascii of each letter within the url path; but I'm actually going to accumulate them and use as an int value.

    I'm getting this error in the debugger: "cannot read property 'length' of undefined" for this part of the code

    Code:
    for (var i = 0; i < path.length; i++) {
        ...
    }
    But I've assigned the returned value of grabURL function to variable path

  12. #12
    Join Date
    May 2014
    Posts
    1,017
    Probably means 'path' -- which should equal tabArray[0]-- is not a string. I really don't know enough about the webkit proprietary chrome.tabs method to say why that would be as I really don't know what that would be returning as a value. It should be returning the tab object, not the path said tab is pointing at -- so that's likely your problem.

    Having trouble finding just exactly what each array index would be for an object type. I THINK it should be returning this object:

    https://developer.chrome.com/extensions/tabs#type-Tab

    In which case if you want the URL the tab is pointing at, it should be:
    Code:
    	chrome.tabs.query(
    		{active: true, lastFocusedWindow: true},
    		function(tabArray) { path = tabArray[0].url; }
    	);
    Though those docs mention something about it being an optional value that is "only set if the tabs manifest is true" or some such... I'd probably do something like this:

    Code:
    	chrome.tabs.query(
    		{active: true, lastFocusedWindow: true},
    		function(tabArray) { path = tabArray[0].url ? tabArray[0].url : 'nonbrowsingtab'; }
    	);
    Maybe swapping 'nonbrowsingtab' for some random value, or maybe the tab's index or windowID.

    Gah, Google's documentation for that sucks.
    Java is to JavaScript as Ham is to Hamburger.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles