Doing things on a new page - javascript

Quick question about going to a new page and doing stuff.
// doesn't work
function doThings() {
document.location.assign("http://foo.com");
things.doIt();
}
foo.com has a things.doIt() function that I want to invoke after switching to that page, but it appears I can't really do that. Is there an easy way to do this?
And side question, I see everyone using document.location = url even though location is an object; it appears to work fine but why does everyone use it? Is it faster?
Edit: I can't edit anything on foo.com.

What you could do is pass a "referer" or action key in the URL query string so that foo.com can tell if it was arrived at from a specific page or should do something special. Note: someone could just manually add it to the URL as well though.
http://foo.com?referer=bar.com
or
http://foo.com?action=doIt
Anyway, what you would want is to have a window.onload event handler on foo.com, and inside it have a function to run onload and check if there exists a key in the query string that matches what would be set from the referer, and if so, run things.doIt()
window.onload = function(){
//check the value of location.search for your query string
//execute special code if so
}

Related

javascript function to redirect any time a specific url is reached?

I'm a student learning JavaScript. I don't know how to do this, but I imagine there has to be a way to.
I'm looking to reference a script throughout my website so that any time a specific URL is reached (which can be accessed through most pages within the site) the script redirects the page to a different URL just after the original URL is loaded.
I'm imagining something like this,though I know this doesn't work:
function urlRedirect (onload = "window.location.href= 'url1.com'")
{
window.location.replace = 'url2.com'
};
I'd also be interested if this possible outside of JavaScript if anyone can think of how to do this. Thanks.
Make sure you read basic JavaScript Syntax first.
I guess that the function you want:
function urlRedirect() {
if (window.location.href == 'url1.com') {
window.location = 'www.url2.com';
}
}
I would assign the function to the window onLoad event.
window.onload = function(){
if (window.location.href == 'http://url1.com'){
window.location.replace('http://url2.com');
}
}
Haven't tested the code but something like that should work.

jQuery unload(): Syntax error after updating a Cookie - how to find the cause?

Solution below: Edit #2
I've a HTML-list the user is able to sort. I don't want to save the data after every drag/drop action, so I save the data on unload: in a cookie and database. Thats working, but:
After saving the data the list is hidden and I get a "syntax error" in this line:
<!DOCTYPE html>
It's strange because everything works fine after refreshing the same page (F5) without changing anything.
I try to find the cause but no success. That's the flow:
1. visit the page (index.php)
2. change the list (set: list_is_dirty = true)
3. click any internal link (call $(window).unload( ... save_data() ... )
4. target page appears without the list (syntax error!)
5. refreshing the page (everything works fine)
Do you have any idea how to find this error? Any tools or strategies? Or maybe the same experience with the unload function?
Thanks in advance!
Edit:
Some code:
var list_is_dirty = false;
// document ready?
$(function() {
function sort_list() {
// some code, not important
}
sort_list();
$(window).unload(function() {
if (list_is_dirty == true) {
/* ---------- HERE's the error! ---------- */
/* The error occures when I try to call the script.php
I tried load(), $.post(), $.get() but nothing works.
The string is correct. I'm not even able to call any of
these functions without params.
*/
// send data to script.php to save data
$("#div").load("script.php?str="+list_data_str);
$.cookie("list_data", list_data_str);
}
});
}
Edit #2 / Solution:
I don't know why, but everything works with window.onbeforeunload instead of jQuery.unload(). An explaination would be great! I'm sorry for this confusing thread!
window.onbeforeunload = function(e) {
$("#div").load("script.php");
}
I think that your issue is with: list_data_str as it's not defined anywhere.
if you are trying to say that you want to do AJAX post for example, then obviously you need to look for success event
else it appears that what your demo code is missing something because you can do it the way you are trying if at the receiving script you use $_GET over the URL and not pay attention to any parameters.. In other words, you are missing the object and when you refresh the page it's loaded into the DOM. Apparently that could be the issue that you are describing, I would suggest that you post a bit more of relevant to your issue code.. like the receiving script or any errors from a debugger like Firebug.
Regarding how to test it, you might want to use console.log in supported browsers or simply alert when is setting up the cookie.
var global list_is_dirty = false;
function sort_list(list, list_is_dirty) {
// some code, not important
//check the list and the flag
//you should return a value, else it does not make sense to use a function here.. note the var defined as global
return list; //?? not sure what to return as don't know what this code does from the posting
}
jQuery(function($)
{
$(window).load(function(e){
var list_data_str= sort_list( );
// send data to script.php to save data
e("#div").load('script.php?str='+list_data_str);
//on unload destroy the cookie perhaps?? or if it's not set a session variable
e.cookie("list_data", list_data_str);
...
The unload event
$(window).unload(function(e) {
$("#div").load("script.php?str="+list_data_str);
$.cookie("list_data", list_data_str);
}
});
}
....
// About your EDIT: Are you passing in here any parameters to the script? Because I think the problem is at that logic.
window.onbeforeunload = function(e) {
$("#div").load("script.php");

Override .load function of jQuery

I have site which uses $(selector).load(path) function in more than 300 pages. Now my client's requirement has changed and I need to access cross domain to call these pages.
For the purpose I have to replace all the .load( function to some cross-domain function with the help of YQL.
Is it possible to override my .load function and call prevent default and do my own code?
There is no clean way to do this, especially since $.fn.load does different things depending on the arguments and replacing it would affect all those subfunctions.
However, jQuery supports AJAX hooks which you might be able to achieve what you want.
In case all you need is support for IE's XDomainRequest, have a look at this plugin: https://github.com/jaubourg/ajaxHooks/blob/master/src/ajax/xdr.js
Anyway, if you really want to replace the ajax load function of jQuery, this code should do it:
var _load = $.fn.load;
$.fn.load = function(url, params, callback) {
if(typeof url !== "string") {
return _load.apply(this, arguments);
}
// do your ajax stuff here
}
This is exactly the same check jQuery uses to decide whether someone wants to bind the onload event or perform an AJAX load.
The most reasonnable way seems to me to not overload the jquery function but simply do a search and replace in your favorite editor to replace $(xxx).load( by yourpackage.load(xxx,.
This can be done in minutes even on 300 js files. Future changes will be easier and the code will be more readable as the reader never expects a jquery function to do something that isn't on the doc.
Yes, it's possible:
$.fn.load = yourFunc;
Is it recommended? I think not.

Javascript windows.location, skipping

I have been having a strange problem with an external javascript file function skipping over windows.location. my program was supposed to take in information from forms then create validate it and after it was validated send it to a php file with get.
I simplified my code to look like
function validation(){
var alerting;//receives from forms commented out
alerting="";
var url="phpadd.php";//after this i would validate it and create the alert but all of that is commented out and irrelevant
if(alerting==""||alerting==null)
{
windows.location=url;
}
else
{
alert(alerting);
}
}
and it didn't work.
Here is the real funny thing
when I include an alert at the end after windows.location it calls the php file. When I don't it doesn't.
for instance
function validation(){
var alerting;//receives from forms commented out
alerting="";
var url="phpadd.php";//after this i would validate it and create the alert but all of that is commented out and irrelevant
if(alerting==""||alerting==null)
{//I also create the code here to put values In the url but I commented them all out so this is my effective code.
windows.location=url;
alert(url);
}
else
{
alert(alerting);
}
}
works but it has to print out the alert first. On the other hand when I don't have an alert after the windows.location call It doesn't work at all.(and I know it works with the alert because It is then redirected to the php file which I know works too). It doesn't have to be alert(url) either It could be alert anything really. in fact it did work with a while(1) loop done afterward but almost crashed the browser first. It's like it is leaving the function before it does what it is supposed to and forgetting about it.
I have tried it in firefox and in google chrome without either way working.
also if you can't find a way to do this. if you could give me a way to take in values from a form to javascript and then send valid values to a php file without windows.location(i've tried every other variant I have found also like: windows.location.href location.href location.assign(url))
I would appreciate it.
by the way The code I left out is not causing the problem because it is commented out where it doesn't work and in the one where it works that is irrelevant because it works it just puts up an alert I don't want.
You should be calling
window.location = url;
not
windows.location = url;

How to code firefox extension which run javascript code in the page's context like firebug does

I know that for safety reasons that this is not easy to achieve, however there would be a way to do so as firebug does...
Please help, would like to invoke some script in the page's context to achieve some effect...
Basically, I would like to achieve two functionality:
1. add jQuery to any web page automatically if not already exist.
2. when open certain address, call a method of that page to auto notify the server. (an ajax functionality of the page)
I have tried to inject on the body, no luck.
tried to get the window object, which however do not have access to call the function.
Will try to change the location to something like: javascript:alert('test inject');
Many thx.
OK, after reading some official documentation and the GreaseMonkey's source, I get the following method which basically works for me.
Hope it will save sb's hour:
var appcontent = document.getElementById("appcontent"); // browser
if (appcontent) {
appcontent.addEventListener("DOMContentLoaded", function (evnt) {
var doc = evnt.originalTarget;
var win = doc.defaultView;
var unsafeWin = win.wrappedJSObject;
// vote.up is the function on the page's context
// which is take from this site as example
unsafeWin.vote.up(...);
}, true);
}
}
Greasemonkey does that. If you are developing your own extension with similar functionality, you can use Components.utils.evalInSandbox.

Categories