JQuery selector not working intermittently - javascript

I am writing a crawler which goes through pages if it detects a ">" type button on current page. Code fails about 1 time out of 100 with error "Uncaught TypeError: Cannot read property 'innerText' of undefined". In attempt to troubleshoot I open Chrome's developer console and test the selector on that specific page manually. It always returns what I expect and the button is visually there. I am puzzled why it fails only rarely and at the same time page where it fails looks normal. Any suggestions how to isolate the problem?
Code:
lastButton = $(".button a").last()[0];
if(lastButton.innerText === ">") {
next(lastButton.href, "getFriends", id);
}

At what point does your crawler run that selector? If the page isn't completely finished rendering yet, because the DOM isn't ready, or the code on the page maybe hasn't finished building out the page, your call to $(".button a").last() would return an empty array. Since you can access any index off that empty array still, when you try to grab the first item out of it you'll get undefined, which would then result in an error when you try to call .innerText off of it.
Try logging how many items are being returned by the selector to see if that is the case.

Found that code in question actually works fine 100% of time. The problem is somehow related to my crawler executing a different scrape function without loading the page for that function. So the peculiar intermittent problem is somewhere else.
Thank you for all who tried to help!

Related

Webpage not displaying from the beginning of the page

So I have a webpage that doesn't load from the top of the page. When the webpage loads, it automatically goes to an image. I think I am experiencing this because of two issues.
I think it has something to do with the line
$( 'html, body' ).animate( {scrollTop: $( '#' + image_container.attr( 'id' ) ).offset().top }, 500 );
Can someone explain what it's doing? I'm not sure how the scrollTop is working in conjunction with animate and the offset() function.
While I was tracking down the line above, I experienced something strange with the following code.
#In file 1
console.log("1")
console.log(function1())
console.log("2)
#In file 2, this is where the line of code from the first part of my question resides
function1(){
some_code_here;
return true;
}
I wanted to see exactly what my question for part 1 was doing so I did a console.log before and after the function while also doing a console.log on the function itself. The console prints out 1 and 2 fine. However when it comes to function1() I get undefined. I was expecting true. I actually added the line return true myself to file 2 because it was giving me undefined. However by adding the return statement I still got undefined.
Since the google chrome inspector is telling me undefined instead of an error, I know that function1() has been accessed, but why is it not printing true?
Lastly, in an attempt to try and stop the webpage from displaying at where the image is (rather than at the beginning of the webpage), I tried window.scrollTo(0,0) in file 1 but that doesn't seem to work for me unless I comment out the call to function1().
Does anyone know what I'm missing?
Turns out the problem to 2 was because the chrome inspector wasn't updating the javascript that I was editing. I had to go chrome inspector then to the Network tab and check Disable cache.
You can check whether your javascript is being updated by going to the same Network tab and select the js file.
I also restarted the server after that but I think by disabling the cache would have done it.

Bookmarklets doesnt work when run from bookmark, but works from console

I am trying to create a bookmarklet that will insert some text in a textarea on a webpage (webpage is for internal use so no point in linking).
Here is example of javascript code i tried:
(function(){document.getElementById("textareaID").value="Some text";})();
I'd like to point out that i tried different element selectors (byClass, query...) and different attributes (even tabindex) to the same result. Also tried in both Chrome and IE11.
So, for some weird reason my javascript runs when i run it from console (or as a snippet) but i get an error "Cannot set property 'value' of null" when i try to run it from bookmark menu.
I tried creating a bookmarklet by myself
javascript:(function(){document.getElementById("textareaID").value="Some text";})();
and tried using online bookmarklet creators to encode special characters
javascript:(function(){document.getElementById(%22textareaID%22).value=%22Some%20text%22;})();
but no luck.
Bookmarklets definitely work on a page (tried with alert "Hello") but i seem to have a problem "capturing" elements.
Also i noticed that ID's of some elements change sometimes (not sure why though), but i always inspect to make sure that ID i try to use exists or i use some fixed value like tabindex. Besides, as i said it works when run from console, so i couldn't have screwed it up somehow... or could have i?
So the problem was execution context.
Because IDs of elements were changing i had to inspect them before running js from console and inspecting changes the execution context from top to wherever the element is. That's why it was working from console and not from bookmark...
So, to write into a textbox inside specific frame:
let Iframe = document.getElementById('yourIframe').contentWindow.document
let value = Iframe.getElementById("textboxID").value = "Some Text"
After that only thing left is to wrap everything inside a javascript:(function(){..your code here..})(); to create a bookmarklet.

JavsScript works on browser console, but not when i put in developers console

I'm trying create a responsive iframe (visualforce page). When I write this in the browser console it works:
document.querySelector('.oneAlohaPage>iframe').height = '300px'
However when I put it in the developers console, I get this error message:
Uncaught TypeError: Cannot set property 'height' of null
I have tried to put it inside a $(document).ready() and window.onload and it still does not work. I also tried window.setTimeout() too.
Can someone help me? Thanks!
$(document).ready() and window.onload you have already tried out, and also window.setTimeout(). Ideally one of this should have solved the issue. But seems it is not resolving in your case. Does the iframe has an 'id' ? You can try with 'id' selector inside setTimeout(). Sometimes parsing through the DOM and using >, + operators results in null object if dynamically rendered.
Wanted to post this as comment but unable to.

FancyBox Jquery Null Error - Strange issue

I am experiencing a very strange issue i am hoping someone can answer (its kind of broad, but i will explain it my best), code works on local page when opened, but as soon as the same page is uploaded it throws an error. Two others have also looked at this, resulting in more confusion.
I downloaded FancyBox to use the inline feature to pop up a user form via href link, instead of taking the user to an additional page.
You can see the "stock" fancy box here:
1 fancyapps.com/fancybox/demo
Under various options, Inline is what i am using.
I didnt need all of the other features that came with FancyBox so i stripped the page to the following, which works just fine:
2 *Fancy Box Demo Stripped to Inline Feature only*
So then, i applied this code to our sandbox copy of the page to implement:
3 *Sandbox Copy with Fancy Box inline feature added to "make offer" link*
It stops working! There are no conflicts with other javascript on the page, and the only difference is that it has a couple of color .css changes, all .fancybox was named to .ptroffer and that the css code is not inline on the page (which wouldn't cause this error anyway).
This same page, opened locally works beautifully - upload and it throws error.
SCRIPT5007: Unable to get value of the property 'ptroffer': object is null or undefined
<script type="text/javascript">
$(document).ready(function() {
$('.ptroffer').ptroffer();
});
</script>
Works fine with link #2, and with link #3 locally, but with #3 uploaded it throws error.
Please!
Something in your code somewhere is overriding $. If you change that "ready" handler to call
jQuery('.ptroffer').ptroffer();
you won't get that error. However, things may not work; I think that an older version of jQuery is being imported by something (1.3!), which is bad.
edit oh I see, something's pulling in Prototype. You've got a regular script soup going on there, and things are going to be unpredictable and bizarre until you get that straightened out. Probably somewhere in there something's calling jQuery.noConflict(), but that "ready" handler you're adding isn't written to expect that. Whatever code that's expecting jQuery 1.3 may be in for a surprise also.

JavaScript error in Safari, only sometimes

I have a webpage that is using jQuery to hide divs on the page load and show them later based on user interactions.
In my $(document).ready() I execute a bunch of code to hide these divs and to bind a function to the click() handler from jQuery for the regions that trigger showing these divs. It also grabs some values out of the HTML to be used by scripts later. The latter is what's causing an issue.
This code works fine in Firefox and Chrome/Chromium (we're still working on the CSS for IE, but the JS works as far as I can tell). In Safari, it works flawlessly about 70% of the time. Every few page loads however, a line in my $(document).ready() gives me an error and stops the JS from executing, also halting the drawing of HTML for the rest of the page.
the line is:
var itemCount = document.getElementById('itemCount').innerHTML;
The debug console in Safari says "Null Value". The thing is, I see the following in my HTML (from the "view source" of the page after it failed to load right):
<div id="itemCount" style="display:inline">0</div>
and it is the only item with this id (obviously.)
I'm thinking that somehow the JS is getting run before the document is actually ready, and was thinking I'd try testing to see if document.getElementById('itemCount') returns null and wait for a bit if it does, but I don't know if this would work, or if there is a less ugly solution.
Let me know if I'm missing something obvious, or being dumb some other way.
From the way your code is written, I think there must be some other error on the page that is causing this. Your first code block should be:
var itemCount = $('#itemCount').html();
...and the second:
<span id="itemCount">0</span>
A <div> set to be displayed inline is a <span>. A <span> set to be a block-level element is a <div>. That's the only reason there are the two tags. They're otherwise identical. Use the right one for the task.
Not that I expect either of these changes to change your symptom. I just suspect you have other...questionable things on your page, and that's what's really causing the problem. Wild guess: move the <script> block containing the ready() handler to the bottom of the document's <body>.
If you're not already using Safari 4, by all means do so. Turn on the Develop menu in the advanced preferences, then say Develop > Show Web Inspector before loading your page. If there are errors, it will do a better job of showing you why than Safari 3.
Seems to be an old bug. See ticket 1319 and ticket 4187.
See this potential workaround:
After some experimenting and deleting 99% of this post :) - adding an empty style tag dinamically magically fixes the problem:
(function(){
if (!/WebKit/i.test(navigator.userAgent)) return;
var el = document.createElement("style");
el.type = "text/css";
el.media = "screen, projection";
document.getElementsByTagName("head")[0].appendChild(el);
el.appendChild(document.createTextNode("_safari {}"));
})();

Categories

Resources