open url using javascript - javascript

I need a way to load a website - something like gBrowser.loadURI, window.location or window.open - but I need to execute some more code AFTER that website has been loaded (and parsed by the browser). The functions I've mentioned don't block execution of my code until the site is fully loaded, but only until it has started loading.
In case it matters: This code will not be part of my/a website, but will be a FireGestures script.

https://developer.mozilla.org/en/Code_snippets/Tabbed_browser#Manipulating_content_of_a_new_tab seems to be what you want. They suggest:
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.addTab("http://www.google.com/"));
newTabBrowser.addEventListener("load", function () {
// use newTabBrowser.contentDocument to manipulate DOM
// or do whatever you want on-load
}, true);
See also docs for tabbrowser and browser.

Related

Injecting javascript into zombie.js

Hi I was wondering if there is the ability in node js and zombie js to inject javascript files in to the headless browser, similar to what you can do with phantomjs.
For example in phantom js you would do:
page.injectJs("amino/TVI.js")
I have used phantomjs and it does do what I want it to do but however I am testing other options due to the high memory required by using phantom js.
you can append script tag into document object since it support DOM API in zombie.
The following example shows how to insert jquery into zombie homepage:
var Browser = require("zombie");
var assert = require("assert");
// Load the page from localhost
browser = new Browser()
browser.visit("http://zombie.labnotes.org/", function () {
assert.ok(browser.success);
// append script tag
var injectedScript = browser.document.createElement("script");
injectedScript.setAttribute("type","text/javascript");
injectedScript.setAttribute("src", "http://code.jquery.com/jquery-1.11.0.min.js");
browser.body.appendChild(injectedScript);
browser.wait(function(window) {
// make sure the new script tag is inserted
return window.document.querySelectorAll("script").length == 4;
}, function() {
// jquery is ready
assert.equal(browser.evaluate("$.fn.jquery"), "1.11.0");
console.log(browser.evaluate("$('title').text()"));
});
});
Try to think the other way around. You have already everything at your hand in zombie to inject everything you want.
For example: that.browser.window points to the jsdom window that every part of your site javascript is using as a base. So you can access the dom and all other window objects in the page already loaded.
I don't know what you want to archieve with injecting - you should not use it for testing anway, but it looks this is not your actual goal

SharePoint 2013 add javascript after whole page load

Disclaimer: I have no experience with SharePoint2013.
I have problem - I must include/fire some javascript functions after the whole page has been loaded. I tried listening to DOMDocumentReady and window.load events, but sharepoint render the rest of page after those events.
My question is: what I should do to be able to run script after whole page with ajax is rendered.
Also I noticed that page navigation is based on hash (#) part. Obviously I must detect that moment also.
Any help or even link to right page in documentation would be great!
You are right, MANY things happen on page after $(document).ready(). 2013 does provide a few options.
1) Script on Demand: (load a js file then execute my code.)
function stuffThatRequiresSP_JS(){
//your code
}
SP.SOD.executeFunc("sp.js")
2) Delay until loaded (wait for a js file, then run)
function stuffToRunAfterSP_JS(){
//your code
}
ExecuteOrDelayUntilScriptLoaded(stuffToRunAfterSP_JS, "sp.js")
3) load after other stuff finishes
function runAfterEverythingElse(){
// your code
}
_spBodyOnLoadFunctionNames.push("runAfterEverythingElse");
Sources:
executeFunc: http://msdn.microsoft.com/en-us/library/ff409592(v=office.14).aspx
ExecuteOrDelayUntilScriptLoaded: http://msdn.microsoft.com/en-us/library/ff411788(v=office.14).aspx
Cant find a source on _spBodyOnLoadFunctionNames but I am using it in a few places.
good luck.
A documented event registration function that is roughly equivalent of _spBodyOnLoadFunctionNames is SP.SOD.executeOrDelayUntilEventNotified. Call this to receive notification of the "sp.bodyloaded" event:
SP.SOD.executeOrDelayUntilEventNotified(function () {
// executed when SP load completes
}, "sp.bodyloaded");
This handler actually fires slightly before the _spBodyOnLoadFunctionNames functions.
This reference is for SharePoint 2010, but the SOD utility is present in SharePoint 2013: http://msdn.microsoft.com/en-us/library/office/ff410354(v=office.14).aspx
There are different techniques used to provided our custom JavaScript code loaded before / in the middle / after OnLoad events in SharePoint:
ExecuteOrDelayUntilBodyLoaded.
Sys.Application.pageLoad.
document.ready Jquery.
_spBodyOnLoadFunctionNames.
_spBodyOnLoadFunction.
ExecuteOrDelayUntilScriptLoaded:sp.core.js.
SP.SOD.executeFunc: sp.js.
Sys.WebForms.PageRequestManager.PageLoaded
– ExecuteOrDelayUntilBodyLoaded function is always executed the first (but at this stage we can not access to SP methods). This could be usefull to execute our custom code at really earlier stage in the OnLoad process.
– There are two SharePoint onLoad functions _spBodyOnLoadFunctionNames and _spBodyOnLoadFunction. Always executed in the order. SO, if we want to execute some code after all functions included by us (or other devs) in _spBodyOnLoadFunctionNames, then is useful to use this one _spBodyOnLoadFunction, because is executed the last.
– ExecuteOrDelayUntilScriptLoaded:sp.core.js and SP.SOD.executeFunc: sp.js. are swapping the order of execution in a random way.
– If we want to execute some functions after all functions (SP, after load functions, Yammer, etc.) we can use this function to attach the OnLoad event –> Sys.WebForms.PageRequestManager.PageLoaded.
You can see the whole article explaining each type, pros and cons here: https://blog.josequinto.com/2015/06/16/custom-javascript-function-loaded-after-the-ui-has-loaded-in-sharepoint-2013/
Regards!
https://mhusseini.wordpress.com/2012/05/18/handle-clicks-on-calendar-items-in-sharepoint-2010-with-javascript/
The above link worked for me. He basically uses the ExecuteOrDelayUntilScriptLoaded to launch his calendar hook code after the SP.UI.ApplicationPages.Calendar.js loads.
Then, in the calendar hook he attaches his own function to the:
SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed function.
_spBodyOnLoadFunctionNames.push("LaunchColorCodeCalendarScriptOnReady");
function LaunchColorCodeCalendarScriptOnReady() {
ExecuteOrDelayUntilScriptLoaded(
MyCalendarHook,
"SP.UI.ApplicationPages.Calendar.js");
}
function MyCalendarHook() {
var _patchCalendar = function () {
//Do something to the items in the calendar here
//ColorCodeCalendar();
};
var _onItemsSucceed = SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed;
SP.UI.ApplicationPages.CalendarStateHandler.prototype.onItemsSucceed = function ($p0, $p1) {
_onItemsSucceed.call(this, $p0, $p1);
_patchCalendar();
};
}
Here is nice article how to use the built-in SharePoint SOD (Script On Demand) functionality: http://www.ilovesharepoint.com/search/label/SOD
It works ok both for SP 2010 and 2013.
The idea of on demand script loading make really sense. SharePoint 2010 loads really a lot of JavaScripts - this takes time! So the idea is: first load the HTML and let it render by the browser so that the user is able to read the requested information as fast as possible. And in the second step load the behavior (the JavaScripts).

How can I use jQuery 1.5.2+ on a Firefox addon?

At first I made a function that received a parameter and returned jQuery such as:
function getjQuery(window)
{
/*jquery code*/(window);
return window.jQuery;
}
But then I got an email form the review and they told me I have to use jQuery file with the original file name and completely unmodified.
I started to search for an alternative and found this solution, but there is no way it work.
jQuery object is created, but I can't find any elements. $("#id").length is always 0. With the previous method it was always found.
My current code (which doesn't work)
AddonNameSpace.jQueryAux = jQuery;
AddonNameSpace.$ = function(selector,context) {
return // correct window
new AddonNameSpace.jQueryAux.fn.init(selector,context||contentWindow);
};
AddonNameSpace.$.fn =
AddonNameSpace.$.prototype = AddonNameSpace.jQueryAux.fn;
AddonNameSpace.jQuery = AddonNameSpace.$;
The jQuery file is loading on my browser.xul overlay:
<script type="text/javascript" src="chrome://addon/content/bin/jquery-1.5.2.min.js" />
Am I loading in the right place?
How can I use jQuery to modify the content on a page (HTML) with the original jQuery file, is it even possible?
You need pass the e.originalTarget.defaultView on the second parameter on jquery..
If you don't jquery will use window.document, which is the window.document from the xul.
Use
gBrowser.addEventListener("DOMContentLoaded", function (e) {
$("#id", e.originalTarget.defaultView).length
}, true);
instead of
$("#id").length;
And, for avoid conflicts with other extensions don't use script in the xul page, use MozIJSSubScriptLoader.
Components.classes["#mozilla.org/moz/jssubscript-loader;1"]
.getService(Components.interfaces.mozIJSSubScriptLoader)
.loadSubScript("chrome://youraddon/content/jquery-1.5.2.min.js");
If you use this method, you load jquery only when you need, avoiding memory leak.
The preferred way to load it is with mozIJSSubScriptLoader so you don't collide with other's extensions. I'm not sure why you're having problems, I can use jQuery in my addon like $("#id").hide() with no additional code (although from the sidebar, now browser.xul).
Either way, this blog post provides a pretty good guide and even has an example xpi to download.

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.

loading javascript dependencies on demand

I'm sure there are different approaches to this problem, and I can think of some. But I'd like to hear other people's opinion on this. To be more specific I've built a widget that allows users to choose their location from a google maps map. This widget is displayed on demand and will probably be used every 1 out of 10 uses of the page where it's placed. The simplest way to load the dependency for this widget (google maps js api) is to place a script tag in the page. But this would make the browser request that script on every page load. I'm looking for a way to make the browser request that script only when the user requires for the widget to be displayed.
function loadJSInclude(scriptPath, callback)
{
var scriptNode = document.createElement('SCRIPT');
scriptNode.type = 'text/javascript';
scriptNode.src = scriptPath;
var headNode = document.getElementsByTagName('HEAD');
if (headNode[0] != null)
headNode[0].appendChild(scriptNode);
if (callback != null)
{
scriptNode.onreadystagechange = callback;
scriptNode.onload = callback;
}
}
And to use (I used swfObject as an example):
var callbackMethod = function ()
{
// Code to do after loading swfObject
}
// Include SWFObject if its needed
if (typeof(SWFObject) == 'undefined')
loadJSInclude('/js/swfObject.js', callbackMethod);
else
callbackMethod();
You might want to take a look at jsloader: http://www.jsloader.com/
Gaia Ajax does this (I know since I implemented it - I'm the original founder) and they're GPL. So unless you're afraid they'll sue you (they're FUDding me with lawsuits now) you might want to check out how they do it. Basic technology is to inject a script tag using DOM when script is needed. Though you must take care NOT to reference stuff in this file before it is finished loading (which happens asynchronously)
The solution to that problem (one solution) is to add up a variable at the bottom of the file and use recursive setTimeout calls to check if the variable is defined and defer execution of the code depending on the file being finished loading until that "bottom of JS file" variable is defined...
We actually also tracked which files where included by appending the hashed value of the filenames into a hidden field on the page. This means we never ended up including the same file more then once...
Pretty nifty in fact...
You might want to take a look at a real DEMO on real estate site.
On the demo page, just click on the link [Xem bản đồ] to see the map loaded on demand.
The map loaded only when the link be clicked not at the time of page load, so it can reduce page download time.
The Google AJAX APIs provide dynamic loading for Google's JavaScript APIs. There is an example of loading the Maps JS on-demand in the documentation:
function mapsLoaded() {
var map = new google.maps.Map2(document.getElementById("map"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
}
function loadMaps() {
google.load("maps", "2", {"callback" : mapsLoaded});
}
you can load script dynamically by adding <script src="..."> tag to DOM tree.

Categories