JavaScript beginner needs help if/then/else - javascript

I need a javascript that reads the QR code, if the URL or instruction shown matches the URL we use, it executes that script
If not, it pops up a warning that the code link is not one of ours, and offers a button to let the user launch the QR link.
Yes, this is a mobile app for my company to check inventory
Here's what I have
if (data.text == 'http://gmail.com') {
window.open(data.text, '_system', 'location=yes');
}
else
{
window.location = 'http://www.jths.co.uk/index.phtml?d=541300';
}
the only part that works (if I remove the rest of it) is this
window.open(data.text, '_system', 'location=yes');

It could be that "data" is undefined or not an object as Sergeon mentioned.
To investigate the issue, you could open browser's Developer Tools, check the console to see if it had any exceptions. You could also put the breakpoint to the line of:
if (data.text == 'http://gmail.com') {
Then you could watch the value of data and data.text or step over.

Related

Shopify page keep refreshing after being redirected by javascript code

I am trying to create a website https://fone-kase-plus.myshopify.com/ that will detect what device model it's being accessed from (for example GALAXY A40) so it will immediately redirect the user to a corresponding page.
It seems to be working, but it will reload the page multiple times after redirecting. If I try to redirect it to non-shopify page (eg stackoverflow.com) this problem doesn't occur.
function deviceAPIcallback(result){
if(result.deviceName == "desktop"){
window.location.href = "https://fone-kase-plus.myshopify.com/pages/galaxy-a40";
}
else{
alert(result.deviceName);
}
}
Can you please tell me what the problem can be or at least how I can detect it by dev tools?
Thanks
When I go to the site from both my macOS laptop and my iPhone I only get the alert aspect of your function. What does result.deviceName return? You might need to add a third '=' to your first 'if' statement.
function deviceAPIcallback(result) {
if(result.deviceName === "desktop") {
window.location.href = 'https...';
} else {
alert(result.deviceName);
}
}

Am I using window.location.replace right? (also am I writing commands right?)

I kind of get all my coding information from the internet rather than a class, and certain answers I can't really understand so hopefully I'll get a simple answer to a possibly stupid question.
In a part of my website, I've got a button which brings up a window.prompt and it asks the viewer if they would like to go to one page (I've called it Timeline because it's a timeline of my art portfolio) or to the other. The prompt works perfectly fine, and I attempted to code it so that if, for example, the user typed in "Timeline" the webpage would automatically redirect them to the Timeline page (which for me is empty at the moment) and vice versa if they typed in "Term 1" (the name of the other page.) I found out about window.location.replace and assumed that it would work if I tried to get it to redirect the user, but when I run my webpage nothing happens after I type in the prompt window. I checked the Developer Tools on Chrome and it didn't report any errors, so is it just me typing some stuff wrong?
function promptFunction() {
var choice = window.prompt ("Would you like to go to the Timeline or to Term 1?")
if (choice === "Timeline")
function redirTime() {
window.location.replace() ("Timeline.html");
}
else if (choice ==="timeline")
function redirTime() {
window.location.replace() ("Timeline.html");
}
else if (choice ==="Term 1")
function redirFirstTerm() {
window.location.replace() ("Term 1.html")
}
else if (choice ==="term 1")
function redirFirstTerm() {
window.location.replace() ("Term 1.html")
}
};
This again is probably me looking for an answer that's right under my nose, so if the answer is something obvious, sorry ^^'
Edit: I've got an answer now; thank you very much! (I did think it was something to do with the way I was typing it, sorry)
The code you posted creates, based on choice a function, but the function is never executed (or you omitted this code).
Additionally the window.location.replace()("...") part is wrong. It calls the replace function on window.location with no arguments and uses the result of this function call again as function an passes e.g. "Timeline.html" as argument.
If all you want to do is setting the location, assign it directly, e.g. window.location = "https://stackoverflow.com" or in your case window.location.href = "Timeline.html" (see https://developer.mozilla.org/en-US/docs/Web/API/Window/location).

Javascript function will not execute using Cookies

I made a javascript function and I am trying to execute it in the javascript area. However, it will not run. When I run the code it just does nothing. I am using Github, so if you want my full code, go to https://github.com/TheNumnut/Wars-of-Shares/blob/master/Login/index.html
I am trying to make a Login page for a game. I would rather use forms than prompts but I have not been able to do that. If somebody could tell me how to use forms I will greatly appreciate it.
This is my code:
function checkCookie(checkusername, checkpassword) {
if (getCookie("username") != "") {
setCookie("username", checkusername, 365);
setCookie("password", checkpassword, 365);
}
else {
if (checkusername != getCookie("username") {
alert("Username wrong");
}
else {
if (checkpassword != getCookie("password") {
alert("Password wrong");
}
}
}
window.open("https://thenumnut.github.io/Wars-of-Shares/", "_self");
}
checkCookie(prompt("Username"), prompt("Password: ");
Please have a look at my other code in Github, because it also has not been working. Especially the profile page. None of the clickable text and links have been working. The link to the Profile Page is https://github.com/TheNumnut/Wars-of-Shares/blob/master/Profile/index.html
Your JS code has syntax errors.
You're missing an extra ) in the 7th, 11th and 42th line.
You can press F12 on your browser and check the console tab, where javascript errors are displayed.
However, I need to agree with the other users that this login method is not a good practice and it's very easy to bypass.
JavaScript source is available to the user of any website. Since the JavaScript runs in the user's browser, the code has to be transferred to the user's browser so the browser knows what to do. This means I as the user can view the source. In this case, by viewing the source I can see the line:
window.open("https://thenumnut.github.io/Wars-of-Shares/", "_self");
So I can bypass your log in page just by looking at the page source and going straight to https://thenumnut.github.io/Wars-of-Shares/

How do we correctly click on a link or button using Javascript?

I'm using the PHP + Ajax version of this template: http://192.241.236.31/themes/preview/smartadmin/1.5/ajaxversion/, Codeception WebDriver (Selenium) to perform my tests. Most of them are working fine, but I have some random, yes, random!, failing tests, so I always get back to them and try to harden, hoping it will not randomly fail sometime in the future. One of the failing reasons are usually due to wrong clicks on the interface. I tell Codeception to click the #element-id and when it fails, I see that it actually had a different page showing in the output png, but the link activated showing it tried to click the correct link. Sometimes I just have to load a different page before clicking that particular link and wait 10 seconds for it to render, and it works, silly huh? Yeah, but sometimes this doesn't work either.
This is how I used to test things:
$I->click('#element-id');
And I have to use the element id, because it's a multi-language app, all (mostly) strings come from a strings file and they might change at some point and break tests.
After too many random tests failing, I decided to make the frontend itself responsible for clicking things during tests, it's a long and silly circunventing shot, but it should be work, so I created a functionalHelper:
public function clickElement($element)
{
$I = $this->getDriver();
$I->executeJS("clickElement('{$element}');");
}
And two Javascript functions:
function clickElement(element)
{
element = jQuery(element);
if(typeof element !== undefined)
{
fakeClick(element[0]);
}
return true;
}
function fakeClick(object)
{
if (object.click)
{
object.click();
}
else if(document.createEvent)
{
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
var allowDefault = object.dispatchEvent(evt);
}
}
I'm using jQuery in the first one because it's already available in the template and it's easier to select non-id'ed things.
This is working fine, and you can test it yourself by
1) Opening the page:
http://192.241.236.31/themes/preview/smartadmin/1.5/ajaxversion/
2) Loading the script in your browser console by executing
loadScript('https://www.dropbox.com/s/kuh22fjjsa8zq0i/app.js?dl=1');
3) And clicking things:
Calendar
clickElement($x('//*[#id="left-panel"]/nav/ul/li[7]/a/span'));
Widgets
clickElement($x('//*[#id="left-panel"]/nav/ul/li[8]/a/span'));
Because the template is using the hash character to control the ajax part of the page and not reload everything, I had to (programatically) add the referer-url to all my href links, so I could, in my app, redirect back to the referer, as the hash part uf the accessed url is not sent to the server. This is a link example:
<a href="/users?referer-href-url=/dashboard" title="Users" id="users-navigation">
<span class="menu-item-parent">Users</span>
</a>
Wich basically means the user was looking at the dashboard when she clicked the users link. If something wrong happens, the app will redirect the user back to the dashboard, with an error message.
The problem is that, somehow, during tests, the current url, when tested using:
$I->seeCurrentUrlEquals('/#/clients?referer-href-url=/clients');
Becomes
/#/clients
Instead of
/#/clients?referer-href-url=/clients
This happens sometimes, because some other it also works. If I browse the site manually it works in 100% of the time and I always see the correct URL in the address bar. And if I manually execute clickElement() it also works fine. The problem only heppens my my suite is running.
Here's an example of it passing (green):
And the exact same test randomly failing (red):
This is the code related to the failing test:
$I->clickElement('#clients-navigation');
$I->waitForText('Jane Doe', 10);
$I->seeCurrentUrlEquals('/#/clients?referer-href-url=/clients');
I usually wait for something after a click, so the page can have time to render.
You can also see that there are a lot of "I click element", using those PHP and Javascript functions without a problem.
I'm using:
Ubuntu 14.04
PHP 5.5.9
Codeception 2.0.7
Selenium 2.44.0
Firefox 33.0
So, what could be the problem here?
Is this the correct way to click an element in Javascript?
In the process I also experience tests which does not fail when ran singly and fails when in batch, but this might be a different question, right?

Is there a method within Omniture's s.code to see whether a pageview has fired?

I'm looking to develop a Omniture "trouble" tag that will fire within Google Tag Manager. This tag should check to see whether the Omniture s.code on-page has fired a pageview. If it hasn't, send an Event to our GA account.
Ideally, it'd look like this (pseudocode follows):
<script>
window.onload=function(){if(OmniturePageViewHasFired == false){
ga('send','event','SCodeMissing','Page',window.location.href);
}}
</script>
Just checking to see whether the s.code is on page at all is a much easier task, but won't be as useful since it's possible for the code to be on page and not have fired. Any ideas? Also note that I do NOT have access to the s.code itself, so I can't set a variable with it that's then picked up by this script.
This is how I'd do it, based on how Adobe's DigitalPulse Debugger looks for it:
function OmniturePageViewHasFired() {
var i=document.images;
for (var c=0,l=i.length;c<l;c++) {
if ( (i[c].src.indexOf('/b/ss/')>=0)
&& (!i[c].src.match(/[&?]pe=/))
) return true;
}
for (var o in window) {
if ( (o.substring(0,4)=='s_i_')
&& (window[o].src)
&& (window[o].src.indexOf('/b/ss/')>=0)
&& (!window[o].src.match(/[&?]pe=/))
) return true;
}
return false;
}
//example:
if (OmniturePageViewHasFired() == false){
// no omn request detected
} else {
// found at least 1
}
Note 1: This will only return true if a page view (s.t) request is made. It will not return true for click requests (s.tl). If you want it to return true for any request, then remove the last &&.. in the 2 conditions.
Note 2: Officially Adobe thinks it is good enough to just look for /b/ss/ in the src. Admittedly, in all my years of QA'ing Adobe Analytics (btw that's what it's called now, not Omniture), I've only seen a false positive from this like one or two times.
If this worries you, you can make the condition more specific by evaluating the domain of the src for your implementation. This is unique to your implementation, which is why Adobe doesn't look for something more specific. Just look at a request on your page to get it.
You can add your own code to track whether or not Omniture has fired.
There is a plugin feature, and Omniture uses to fire plugins and other code on a tracking event. This function is fired everytime a pageview or on-click event, or any other type of Omniture event is fired.
You'll want to make sure that this is not used elsewhere to enable Omniture plugins, if it is, you'll have to be able to update that code. Basically you could do something like the following, as long as you make sure that the following bit of code loads and exectues (after) the s_code.js file loads and executes:
var om_fired = false;
s.usePlugins=true;
function s_doPlugins(s) {
om_fired = true;
}
s.doPlugins=s_doPlugins;
Then in your google code just check to see if om_fired is true/false
Another way to do it (adding it here since it was too long for a comment).
Before s.code loads, add some script that reads the cookies that are set by Omniture, I don't remember the exact cookie names, but multiple cookies are set. Your code that reads the cookie will need to be in the header so it fires as the page loads( and before site cat tracking code), and before page load completes. Read the omniture cookie, and check the values, there is one in there for Time Since Last hit, I believe the cookie variable is something like s.tlh. Store that value away, then after page load fire another call that reads the cookie again and check to see if the tlh value changed. If it did then your tracking event occured. If it did not change, then your event did not fire. Your challenge will be to make sure the code fires in the right order, i.e. 1. Read cookie/store value, 2. Site Cat Fires, 3. Read cookie again and compare w/ cookie in #1.

Categories

Resources