Javascript: Performing action once the next page has loaded? - javascript

I am currently building a google extension and this is what I'm going for:
Do something on awesome.page1.html then automatically press Next Page. When the new page has loaded, fill in a form's textfield.
My issue is that even though I know how to fill in the textfield, I don't quite know how to tell it to fill it in once page2 has loaded. It keeps trying to do everything on page 1.
This is what I'm trying but it's not working:
function addEffect() {
document.getElementsByClassName("effect1 shine")[0].click();
document.getElementsByClassName("nextPage BigButton")[0].click();
nextStep();
}
function nextStep() {
if(document.getElementsByClassName("myformTextField imageName") != undefined) {
alert('Page 2 is up.');
}
else {
alert('Page 1 is still up.');
setTimeout("nextStep()", 250);
}
}
I'm using an alert just for testing, and I keep getting the "Page 2 is up" even though it is still on page 1. I'm checking if an element, which is only present in page 2, is up. How could I make sure page2 is up?

The major issue you're going to run into is that JavaScript variables--including functions--don't persist from one page to another. Put another way, you can't write a function on one page and have it execute on the page that replaces it.
You could pass a URL variable or set a cookie for data persistence--or store settings on your server--but a straight JavaScript approach won't work.
Of course, there is a little trick that some folks use to load the entire DOM of the next page into a variable (using a variation on an XMLHttpRequest), apply the stored settings to the object in memory, and then replace most of the document body with most of the new DOM, but that's probably far more complicated than you need, and it has to conform to same-domain requirements.

Well, your code here:
document.getElementsByClassName("myformTextField imageName")
returns an empty array when it finds nothing, which is not undefined. Therefor, your first if condition will always be true, regardless if it finds your item or not.
Instead, check the length returned by getElementsByClassName or use querySelector and check for null
if (document.getElementsByClassName("myformTextField imageName").length) { ... }
// Or..
if (document.querySelector('.myformTextField.imageName') !== null) { ... }

The easiest method I chose to go with was content script matches.
What I did was create two separate javascript files in my extension: 1.js and 2.js. When awesome.page1.html loads it will run 1.js and when page2.html loads it will run 2.js.
All I did in my manifest.json file is the following:
"content_scripts":[
{"matches": ["http://awesome.page1.com/*"], "js": ["1.js"]},
{"matches": ["http://page2.com/*"], "js": ["2.js"]}]

you should try to user jquery and the $(document).ready(handler)
this is really a best practice to ensure that the page is loaded before it tries to execute your commands
http://api.jquery.com/ready/

Related

Swift - execute Javascript on each page

I have a UIWebView to which I pass a HTML file to load.
The HTML file includes javascript that looks for the existence of a variable.
If it exists, it performs one action, if the variable doesn't exist, the script performs another action.
if(typeof customVar === 'undefined')
//Perform task1
else
// Perform task 2 using customVar
On the native, I use the function stringByEvaluatingJavaScriptFromString to set the variable before the page is loaded.
To do so, I'm setting the code in webViewDidStartLoad (I also tried to place it in shouldStartLoadWithRequest).
func webViewDidStartLoad(webView: UIWebView)
{
let cutVar = "test"
webView.stringByEvaluatingJavaScriptFromString("customVar = '\(cutVar)';")
}
This works well when I load a page for the first time, but only the first time.
After that, it seems that through the webViewDidStartLoad, we re-assign the variable in the current page, and then reload the page itself.
So that means, the page is reloaded without the variable to be set.
Is there a way to say I want to run the javascript bit for the next page to load?
Maybe something like a global variable always accessible?
Thank you.

Changing the value of a variable through user input and re-using it on a different page

First I would like to say that I searched and found plenty of answers and even tried a couple (more than...) but to no avail! The error is probably mine but it is time to turn to SO and ask.
Problem description: I have a variable that I want to change the value through the user input (click on btn). As soon as the user chooses the btn it will navigate to a different page that will use the result of the variable to perform certain actions. My issue is that if I alert on my 1st page I get the value being passed by the btn... But on the second page I only get "undefined"
I think it has to do with variable scope and the fact that (I think it works that way anyway) even a window.var will be deleted/purged in a different window.
Anyway, the code is something like this (on the 1st page/file):
var somAlvo;
$('#omissL').click(function(){
somAlvo = 'l';
window.location.href='index_ProofOfConcept_nivel1.html';
});
And on the "receiving end" I have the following code
<head>
...
<script type="text/javascript" src="testForm_javascript.js"></script>
to "import" the js file with the variable and:
var processo = somAlvo;
alert(processo);
I tried declaring window, not using var inside the function and so on...
This is a proof of Concept for a project in my local University, where I'm working as a research assistant (so, this is not homework ;) )
Thanks for any help/hints...
You are right in that when you navigate to another page, the entire JavaScript runtime is reset and all variables lost.
To preserve a value across page loads you have two options:
Include it as part of a query string when navigating to the new page.
Set a cookie.
You may also want to look into loading the new content through an AJAX call and replacing what is displayed. This way you won't reload the entire page which won't cause the JavaScript runtime to be reset.

How can I clear references to Javascript functions that no longer exist?

I am working on a project that uses AJAX to download HTML, CSS and Javascript in one singe chunk of text then appends it to an element on the page. Here is the code:
_t.stage.empty();
_t.stage.html(DATA);
This works fine.
Here is the problem:
After adding the HTML to the stage, I call this function:
if(initApp != null && typeof(initApp) == "function") initApp();// Checks for initApp(). If exists, executes.
If I load a page that has this function, then load one that does NOT have this function, the function from the first page is executed. Here is some psuedo code to understand the results.
page 1:
This is a page.
<style>...</style>
<script> function initApp(){ alert("hello"); } </script>
When this page is run, an alert box with the text 'hello' is shown.
page 2: (no initApp() function)
This is page 2.
<style>...</style>
When the page is run, an alert box with the text 'hello' is shown.
Please note: These pages are loaded with AJAX and inserted into the HTML of an already loaded page.
It is not easy to tell exactly what you're trying to do, but if what you're trying to do is make it so that some other code that calls initApp() will cause nothing to happen when it calls that, then you can simply redefine the function to a do-nothing function like this:
initApp = function() {}
The most recent definition of a function takes precedence (e.g. replaces any prior definitions).
If your newly loaded code contains an implementation of initApp() that you don't want called the second time the script is loaded, then you're out of luck. You can't stop that. You will need to change the structure of your code so that the dynamically loaded code doesn't execute stuff you don't want to be executed. There are many different ways you could do that. For example, you could have a global boolean that keeps track of whether the init code has been called yet.
var initCalled = false;
function initApp() {
if (!initCalled) {
initCalled = true;
// rest of initialization code here
}
}
initApp(); // will only actually do anything the first time it's called
// even if it is loaded more than once
It appears from the comments that you seem to think that reloading a script tag with different code will somehow make code from the previous script go away. It will not. Once a function is loaded, it stays loaded unless it is redefined to mean something else or unless some code explicitly removed a property from an object. It does not matter how the code was loaded or whether it was in the core page or an external script file.
Javascript functions that no longer exist
This is a bad premise. The functions still exist, which is obvious from the fact that the second AJAX load ended up executing it. The fact that the <script> tags are replaced and no longer in the document doesn't undefine the function. It's like asking why is your TV still broken if the burglar that broke it is no longer there.
There are two basic things you can do:
a) Clear the function explicitly yourself:
if (initApp != null && typeof(initApp) == "function") {
initApp();
delete window.initApp;
}
b) Change the function name to be unique per AJAX page (or namespace the function with the same idea), probably tied to the name of the AJAX page, so you can invoke it in a more specific manner.

Javascript window location in loop on masterpage

We have a site with masterpage. There is another page policy.aspx.
User has to accept the policy in order to access the site resources.
Hence we put the foll. code on masterpage. There is a boolean variable (var boolVal).
if(!boolVal)
{
window.location="http://url/policy.aspx";
}
For new users boolVal is always false. So they get redirected to the policy.aspx page. But since this page also inherits the masterpage, it reloads continuously as it executes window.location again and again infinitely.
Can something be done besides stopping the policy.aspx page to inherit the masterpage?
It's hard to know without seeing the rest of your code, but my first instinct would be to change your code to:
if(!boolVal)
{
window.location="http://url/policy.aspx";
boolVal = true;
}
cut your js in 2 parts:
1 part with declaration.
1 part with the loop.
In policy.aspx js try to insert code between the 2 parties to change the value of the varialble boolVal
Well, if JavaScropt is to blame, I bet problem lies in boolVal.
If it's not defined typeof boolVal is 'undefined'... Which is falsy value that you negate.
if(!boolVal) // will always be true if boolVal isn't defined/inherited properly.

Dynamically Included Javascript and Dependencies

So, as a sort of exercise for myself, I'm writing a little async script loader utility (think require.js, head.js, yepnope.js), and have run across a little bit of a conundrum. First, the basic syntax is like this:
using("Models/SomeModel", function() {
//callback when all dependencies loaded
});
Now, I want to know, when this call is made, what file I'm in. I could do it with an ajax call, so that I can mark a flag after the content loads, but before I eval it to mark that all using calls are going to be for a specific file, then unset the flag immediately after the eval (I know eval is evil, but in this case it's javascript in the first place, not json, so it's not AS evil). I'm pretty sure this would get what I need, however I would prefer to do this with a script tag for a few reasons:
It's semantically more correct
Easier to find scripts for debugging (unique file names are much easier to look through than anonymous script blocks and debugger statements)
Cross-domain requests. I know I could try to use XDomainRequest, but most servers aren't going to be set up for that, and I want the ability to reference external scripts on CDN's.
I tried something that almost got me what I needed. I keep a list of every time using is called. When one of the scripts loads, I take any of those using references and incorporate them into the correct object for the file that just loaded, and clear the global list. This actually seems to work alright in Firefox and Chrome, but fails in IE because the load events seem to go off at weird times (a jQuery reference swallowed a reference to another type and ended up showing it as a dependency). I thought I could latch on to the "interactive" readystate, but it doesn't appear to ever happen.
So now I come asking if anybody here has any thoughts on this. If y'all want, I can post the code, but it's still very messy and probably hard to read.
Edit: Additional usages
//aliasing and multiple dependencies
using.alias("ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js", "jQuery");
using(["jQuery", "Models/SomeModel"], function() {
//should run after both jQuery and SomeModel have been loaded and run
});
//css and conditionals (using some non-existant variables here)
using.css({ src: "IEFix", conditionally: browser === "MSIE" && version < 9 });
//should include the IEFix.css file if the browser is IE8 or below
and to expound more on my response below, consider this to be file A (and consider the jquery alias from before to be there still):
using(["jQuery", "B"], function() {
console.log("This should be last (after both jQuery and B have loaded)");
console.log(typeof($));
});
Then this would be B:
using("C", function() {
console.log("This should be second");
});
And finally, C:
console.log("This should be first");
The output should be:
This should be first
This should be second
This should be last (after both jQuery and B have loaded)
[Object Object]
Commendable that you are taking on such an educational project.
However, you won't be able to pull it off quite the way you want to do it.
The good news is:
No need to know what file you are in
No need to mess with eval.
You actually have everything you need right there: A function reference. A callback, if you will.
A rough P-code for your using function would be:
function using(modules, callback) {
var loadedModules = []
// This will be an ajax call to load things, several different ways to do it..
loadedModules[0] = loadModule(modules[0]);
loadedModules[1] = loadModule(modules[1]);
// Great, now we have all the modules
// null = value for `this`
callback.apply(null, loadedModules);
}

Categories