.text & .attr in Jquery not working in IE - javascript

I am having some trouble getting a function to work in internet explorer (7-8). My problem is that I need to hide some links until a user logs in, I would do this server side; however, suffice to say I have no way of doing this.
My approach has been to load a set of text (login/logout) that will change server side and test for the logout value. I was doing this by loading a div by id in Jquery and using the .text() when IE 7-8 both refuse to run this ie dev tools told me that "object doesn't support this property or method" with a reference back to the line of code containing this lookup. Code posted below:
function logintest(){
login_test= "Sign out";
alert($('#log').text());
login = $('#log').text();
if(login.search(login_test) == -1){
$('#hiddenBox').css('display','none');
}
};
The fun thing is that the alert runs properly and displays the right text string. Upon this failing I tried using the .attr() and got identical results. Any help would be great!
Jquery version: 1.4.4
Site: www.brainwellnesspro.com
IE: 7-8 on win xp

Looking at your site I'd start by fixing the html to be valid, this isn't good:
<div id="log" name="<a href='http://www.brainwellnesspro.com/login.php' onclick=''>Sign in</a> or <a href='http://www.brainwellnesspro.com/login.php?action=create_account' onclick=''>Create an account</a>">
<a href='http://www.brainwellnesspro.com/login.php' onclick=''>Sign in</a> or <a href='http://www.brainwellnesspro.com/login.php?action=create_account' onclick=''>Create an account</a>
</div>
and since you already have jquery you can check the current text value of the login link like this
function logintest(){
if($("#log a").first().text() !== "Sign out"){
$('#hiddenBox').css('display','none');
}
};

My problem is that I need to hide some
links until a user logs in, I would do
this server side; however, suffice to
say I have no way of doing this.
Why Not? Surely your application should know if the user is logged in or not (and be able to render differently accordingly?)
anyway - without seeing your markup (with the context of the element with id='log' (what type of element is this???)....
if(login.search(login_test) == -1)
should probably be
if(login.search(login_test) == '-1')

Related

Page reloads when clicking anchor element

I'm working on a web application which is a traditional aspx (asp.net) web forms app but has had some angular 6 apps incorporated into it.
I've been tasked with fixing a bug that causes the browser to refresh when clicking on an anchor element with a href="#".
I'm not sure what's causing the whole page to reload.
Strangely when I open dev tools in Chrome, choose the network tab and select disable cache the page only refreshes the first time I click a link and any other subsequent clicks work fine. This might be to do with the fact that after the first time I click it the browser url now contains the # at the end of it.
I know this seems a bit random but I wondered whether anyone had any theories on what may cause the reload in the first place.
It's hard to tell what could be causing this without seeing any code. The most common solution I've used when I get this behavior is a prevent default. You can do something like
<a href="#" (click)="$event.preventDefault()">
Or if you already have a click event then pass in $event as a parameter to your function then preventDefault in the function you are calling. This would look like:
Html
<a href="#" (click)="someFunc($event)">
and in your ts:
someFunc(event) {
event.preventDefault();
// rest of your code here
}
This answer is related to the question and it's the first one that comes up in Google so I hope this is useful.
I have some external web components that use regular anchor tags with hrefs that point to routes in my angular app. Clicking the href causes a full page reload. This is because I'm not using routerLink - but, in my case, I can't.
So, my work around is:
#HostListener('window:click', ['$event'])
onClick(e: any) {
const path = e.composedPath() as Array<any>;
const firstAnchor = path.find(p => p.tagName.toLowerCase() === 'a');
if (firstAnchor && !firstAnchor.hasAttribute('routerlink')) {
const href = firstAnchor.getAttribute('href');
this.router.navigateByUrl(href);
e.preventDefault();
}
}
Depending on your application, you might need to make some other checks e.g. is the target _blank, is it an external url etc.
change your a tag code as below
A Tag
this will invoke yourClickEvent(); without page reload
check the stackblitz here stackblitz
If you don't want to reload the page use $event.preventDefault()
<a href="#" (click)="$event.preventDefault()">
Try using debug tools to select the element, then click Event Listeners and then the Click event to see what is listening. Perhaps you can track it down that way.
You could also simply paste this into the console to trigger a break, and then click any of the offending elements:
['unload', 'beforeunload'].forEach(function (evName) {
window.addEventListener(evName, function () {
debugger; // Chance to check everything right before the redirect occurs
});
});
source: Break when window.location changes?
As you are using angular routes, try to use this notation:
<a [routerLink]="['./']" fragment="Test">
As explain by this comment: https://stackoverflow.com/a/38159597/4916355
use href="javascript:void(0);"
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just a short and simple script that evaluates to undefined.
Use [routerLink] instead of using href = "", and use click event to call your calling method in the typescript file.
ex:
// downloading the file based on file name
<a [routerLink]="'file://' + 'path'" (click)="downloadFile(templateDocument.fileName)">{{downloadDocuments.fileName}}</a>
Since you have mentioned the web app is asp.net webforms, can you please let us know
Whether the link is asp.net hyperlink control. If so,
AutoEventWireUp could cause the link to be automatically submitted:
Please have a look at this link
If you do have asp.net server controls on the page, then you could disable by setting
#Page AutoEventWireup="false"
For the entire project, this can be disabled by setting in web.config:

What's the javascript to only click a link if it exists?

I'm in the SeleniumIDE , but calling out to javascript.
Seems like this would be a fairly common scenario for others too.
I have a good test suite but the first thing it does is login.
I would like the suite to start off be making sure I am logged out and if not, logging me out.
I can tell if I am logged in by the presence of a 'Logout' hyperlink
But I only want to click on logout IF I am currently logged in, otherwise I want to do nothing, as trying to click on a non-existent element would raise an error if I am not already logged in)
So logically this is:
if ui element(logout link in my case) exists
click on logout link
else
do nothing
end
I am using the Selenium IDE and calling javascript - Given that I can't do if then in the basic seleniumIDE I was hoping I could do this in javascript itself.
something like:
store javascript{if ([a with text 'Logout' exists]) then click on it end;} id1
although instead of click on it [this], it would also be ok (though more brittle) if I just visited the url which is
http://my-apps-domain/users/sign_out
but I'm not sure of the exact syntax.
The relevant HTML is:
<li>Logout</li>
If it exists I would like to click on the a (or visit the url directly), otherwise nothing.
I would like to find a non-jquery solution if possible.
Update: I have found that even javascript{window.location.replace('http://google.com') } closes my seleniumIDE window and replaces it with google but doesn't affect the actual window where the tests themselves were running.
Triggering a click event in raw JavaScript can be tricky (check out this answer: https://stackoverflow.com/a/10339248/2386700)
However, if you can also use jQuery, that would simplify things. For example, if the logout button has an id like "logout" then you could do something like this:
var logoutButton = $('#logout');
if (logoutButton != null) {
logoutButton.click();
}
Since you don't have control over the HTML, I suggest referencing the link in another manner. The URL seems very reliable for that purpose:
var logoutLink = document.querySelector('a[href="/users/sign_out"]');
if(logoutLink != null) {
window.location.href = logoutLink.href;
}
You don't need to fire any kind of click event, because page navigation can easily be done with window.location.
UPDATE:
Another idea is to assign your button an id, then click it with selenium:
var logoutLink = document.querySelector('a[href="/users/sign_out"]');
if(logoutLink != null) {
logoutLink.setAttribute("id", "logoutLink");
}

Element is not displaying on FireFox & Opera, but on Chrome & Safari is working

I have a problem where an element is not showing on Opera nor Firefox. Using firebug on Firefox I could see that an error saying that a function I use to initialize the code 'is not defined'
Now here's the thing, when I empty the cache on the Firefox browser, I can see my element which contains a "facebook button" and the error is gone, but once I refresh the browser I can't see my element and returns the error again. I would have to empty out the cache in order to see the button once again.
The element is supposed to be triggered with jQuery to show if a facebook user is online, and if not it will show that button. But this is only working on Chrome & Safari, and I believe on IE8 (which i don't have) but someone told me it worked.
This is the code to show the element on my Javascript file:
jQuery('#fbLogin').show();
Now, if i was to change this on my .css file:
#fbLogin {
display:none;
}
to this:
#fbLogin {
display:block;
}
it will display, but the problem i saw was that it showed all the time, and this needs to be hidden if the user is logged in. I basically have a code that says .show the button and .hide if logged in...
here's a link to a page if you want to take a look further:
http://gullypost.com/entertainment/tim-westwood-kendrick-lamar-interview/
On Safari & Chrome you will notice that the facebook button shows up on the right sidebar, but not visible on the other browsers.
Can someone help me solve the problem to this? Thanks.
There's a weird problem when using jQuery when trying to use .show() on an element that doesn't have a defined height. The fix is to set the height either explicitly or dynamically.
​$(selector).height(function() { return $(this).height() });​​
It looks like the second time the page loads, you're getting the following JavaScript error:
fb_og_actions_init_vid is not defined
The file that contains the function is being added to the page correctly. My only guess would be to try and move the reference to the function:
fb_og_actions_init_vid("Connected to Facebook", "108821");
To within a document.ready function:
$(document).ready(function(){
fb_og_actions_init_vid("Connected to Facebook", "108821");
});
I believe this will work:
document.getElementById('fbLogin').style.display = 'block';

How do I discover which function is called when I press a button?

I'm stuck modifying someone else's source code, and unfortunately it's very strongly NOT documented.
I'm trying to figure out which function is called when I press a button as part of an effort to trace the current bug to it's source, and I"m having no luck. From what I can tell, the function is dynamically added to the button after it's generated. As a result, there's no onlick="" for me to examine, and I can't find anything else in my debug panel that helps.
While I prefer Chrome, I'm more than willing to boot up in a different browser if I have to.
In Chrome, type the following in your URL bar after the page has been fully loaded (don't forget to change the button class):
var b = document.getElementsByClassName("ButtonClass"); alert(b[0].onclick);
or you can try (make the appropriate changes for the correct button id):
var b = document.getElementById("ButtonID"); alert(b.onclick);
This should alert the function name/code snippet in a message box.
After having the function name or the code snippet you just gotta perform a seach through the .js files for the snippet/function name.
Hope it helps!
Open page with your browser's JavaScript debugger open
Click "Break all" or equivalent
Click button you wish to investigate (may require some finesse if mouseovering page elements causes events to be fired. If timeouts or intervals occur in the page, they may get in the way, too.)
Inspect the buttons markup and look at its class / id. Use that class or id and search the JavaScript, it's quite likely that the previous developer has done something like
document.getElementById('someId').onclick = someFunction...;
or
document.getElementById('someId').addEventListener("click", doSomething, false);
You can add a trace variable to each function. Use console.log() to view the trace results.
Like so:
function blah(trace) {
console.log('blah called from: '+trace);
}
(to view the results, you have to open the developer console)

Updating iframe 'src' on button press (a form ' file' button)

First let me say i dont know if this is possible the way im doing it so, i come here to the pros for help.
As the subject points out, What im trying to achieve is, that on button press, the content i want loaded appears in an iframe....
At first, what i did is this:
The iframe html is this:
<iframe id="my-frame" src=""></iframe>
and the simple form code is this:
<form action="#" method="post" target="my-frame">
<input type="file" name="localFile" id="localFile">
<input type="submit" id="Sbtn" name="Sbtn" value="submit">
</form>
Which should load what i selected inside the iframe i targeted called "my-frame" but instead, when i press
the button, it loads the currently opened page and i end up with like, one of those funhouse mirror effects that you see the same thing over and over and over inside itself.......or loads nothing at all, the iframe section stays white....
So i gave up and tried a bit of Js and again, not sure if this is the way to go about it but...well i gotta try something. So that said, i took out the "target="my-frame" from the form part of it, and put in this.
var myFrame = document.getElementById("my-frame");
var btn2 = document.getElementById("Sbtn");
var field2 = document.getElementById("localFile");
btn2.onclick = function(){
if(field2.value ==""){
//enter error message or something.
} else {
myFrame.src = field2.value;
return false;
}
}
Then when i do this, i get errors like "page cannot be found" etc...not matter what i do the page cant be found.
the exact error i get is this:
Error 6 (net::ERR_FILE_NOT_FOUND): The file or directory could not be found.
to which i dont understand since im navigating to the file(whatever it is) via the wizard that comes up.
Now for further troubleshooting, when i do a regular link ...for example(pseudo code)
then it loads it in just fine...
so im lost.
Any ideas as to what im doing wrong or...something im missing?
Any tips,links, any help of any kind ill gladly and humbly accept.
thanks in advanced.
Somdow
http://somdowprod.net/
As I understand, what you want is:
Pick a file with an input type=file
Click submit
The selected file should appear inside an iframe (what you expect)
AFAIK, this can be done only with IE. Cause of the security settings for Chrome & FF are different (higher). You can try an alert command to see what really happen whith IE, Chrome & Firefox. Just change your code a bit like this :
...
} else {
alert(field2.value); ///--- add this line
myFrame.src = field2.value;
return false;
}
...
Open your file with all 3 major browsers (IE, Chrome, FF) & see result for each one when you choose file and click the submit button repectively.
As I tested, the result for IE was the full path on hard disk to the file :
C:\Documents and Settings\DUNGPRO\My Documents\A WALLPAPER\abc.jpg
While Chrome replace the path with a fakepath:
C:\fakepath\abc.jpg
And firefox just give you the filename only:
abc.jpg
Yes, the fake path or filename only are what make it displayed 404-File not found. Only IE gives you the expected path & that's why your code works properly with IE.
Hope you don't feel this is too bad, while almost these settings from Chrome & FF are default and impossible to change whithin your code. Just think they're for user's security & find another approach. Good luck.

Categories