The title is the best way I could sum it up. It's a little fuzzy on how to explain this.
Basically, if I include the javascript file holding the JSON function from within an html file, then trigger the JSON function - callback works. However, if I just call the JSON function from within it's own file - callback never fires. Not sure if this is some sort of javascript or web browser security feature. Would be greatful for an explanation.
Here are some examples.
Working version:
json.html: (trimmed down)
<html>
<head><script type="text/javascript" src="json.js"></script></head>
<script>
JSON_Object(json_url, function(json_obj) {
alert(json_obj); // this version works!
});
</script>
<html>
json.js:
function JSON_Object(json_url, callback) {
// This function will return an object to the JSON data.
json_url = json_url + "&callback=jsonCallback";
var json_script = document.createElement("script");
json_script.setAttribute("src", json_url);
json_script.setAttribute("type", "text/javascript");
window.jsonCallback = function(jsonObjReturn) {
// cleanup
document.body.removeChild(json_script);
delete window[callback];
callback(jsonObjReturn); // use our callback function to return the data.
}
document.body.appendChild(json_script);
}
Non-Working version - Another function inside json.js:
JSON_Object(content_page, function(json_obj) {
alert(json_obj); // This version doesn't work. Never called.
});
After a bit of research, I found that I was right. It IS a web browser security feature for extensions.
From the following link:
http://code.google.com/chrome/extensions/content_scripts.html
Quote from the page
However, content scripts have some limitations. They cannot:
Use variables or functions defined by their extension's pages
Use variables or functions defined by web pages or by other content scripts
JSON falls into the above categories because it uses a function for it's callback.
Related
Here is my library code:
function simpleEdit(){
var cell = SpreadsheetApp.getActiveSheet().getActiveCell();
cell.setValue('Simple edit made by script');
// Calling a custom script function after doing edit
customfunc();
}
customfunc() is outside the library in other script but in same project.
Here is its code:
function customfunc() {
SpreadsheetApp.getActiveSheet().getRange('F2').setValue('Hi');
}
Script calling library function
function s()
{
Demog.simpleEdit();
}
Demog is the library identifier
Yes this works. If you have a library published with two script files in it. All the methods not marked as private will be accessible to script the is utilizing the library.
But to let you know getActiveSheet() or getActiveSpreadsheet() will not work in a library. Even if the script you published was contained in a spreadsheet. It will always return null.
I am dealing with this problem from quite a while, please suggest me a solution:
For android app development, I am using phonegap framework.
I have a async function readFromFile() which reads the json file (which is updated using a user data everytime) stored in SD card, and stores the text result into the global variable, Next I have a function populatePageContents() which reads the global variable, and populates the page's html from the json data.
I want the populatePageContents() function to be called after readFromFile() function has finished reading the file data into global variable.
I tried using someting like this:
<script type="text/javascript">
globalVariable = '';
readFromFile(); // Uses phonegap's file API to read file and puts result into global variable
setTimeout(function() { populatePageContents(JSON.parse(globalVariable)); } , 500);
</script>
The above method works sometimes, but not always. Please suggest some better use of callback functions. Thanks!
Please use callbacks for making it work everytime
U can use something like this:
readFromFile(function(data){
populatePageContents(JSON.parse(data));
});
And your readFromFile function should look like this :
readFromFile(callback){
/***read file phonegap code***//
callback();
}
I have an html editor custom control that I've been working on that has a basic undo/redo function that works well with all the functions that are part of the editor. The undo/redo function works off of 2 stacks (respectively named UndoStack and RedoStack), which when one of the other editor functions that modify the text property of the editor occur push on to the UndoStack. For visualization, when Undo is clicked, pop is called and that value is stored to the redo stack.
However, the editor also interacts with some on-page AJAX functions that allow the user to insert already written text stored in our database. What I want to accomplish here is to include the the JavaScript that is used to run the editor on the page and call the functions needed to push text on to the undo stack from the page.
As a side note, I used the solution provided by Rob2211 on Embedded dll resources to get the script file on the page in question, but I would like to know how to call a function from it as it keeps saying that the function I want to call (pushUndoStack(), excuse the lack of creativity) is undefined.
Thanks
P.S. I generally code in C#, but some of the project is in VB.NET
Code Snippets: On Page
Register Page Directive
<%# Register Assembly="WebControl.HtmlEditor" Namespace="WebControl.HtmlEditor" TagPrefix="ec" %>
Code that grabs the HtmlEditor.js function
<script type="text/javascript" src="<%= HtmlEditor.Resource.GetClientScript(Me.Page, "HtmlEditor.js")%>"></script>
Code Snippets: In C# file
The Resource Class
public class Resource
{
public static string GetClientScript(Page p, string file)
{
return p.ClientScript.GetWebResourceUrl(typeof(Resource), typeof(Resource).Namespace + ".Scripts." + file);
}
}
The assembly reference:
[assembly: WebResource("WebControl.HtmlEditor.Scripts.HtmlEditor.js", "text/javascript")]
The Prototype function: (Contains the following undo/redo functions)
WebControl.HtmlEditor.HtmlEditor.prototype =
{
.
.
.
}
From the Embedded JavaScript File: All undo/redo related functions.
getUndoStack: function () {
return this.undoStack;
},
pushUndoStack: function (value) {
this.undoStack.push(value);
},
popUndoStack: function () {
return this.undoStack.pop();
},
getRedoStack: function () {
return this.redoStack;
},
setRedoStack: function (value) {
this.redoStack = value;
},
clearRedoStack: function () {
var redoStack = this.getRedoStack();
redoStack = new Array();
this.setRedoStack(redoStack);
},
pushRedoStack: function (value) {
this.redoStack.push(value)
},
popRedoStack: function () {
return this.redoStack.pop();
}
I solved this using jQuery. Since the JavaScript function I needed was embedded in the HTML Editor custom control, the function that I needed was already available to the page, it just needed to a way to get to it. Using the $find('ControlID') method, I was able to search the DOM tree for the ID of 'Editor' and access everything that was included with the control, in this case, the function called pushUndoStack(). What lead me to this conclusion was a another part of this project that did the spell checking component of this project.
Thanks to #AndrewWalters and #TsanyoTsanev for the help.
I need to execute some JavaScript string code from flash swf file using actionscript 3.
I read that it could be done by passing the JavaScript code to the parent html document , using externalinterface.call function. Then I assume it will be faster if I can declare functions in the JavaScript code in the HTML document in the first use of externalinterface.call function ; if flash code calls the JavaScript code repeatedly. So let me ask you how to do that. For details , any JavaScript to be loaded is unknown in design time and I can not prepare a JavaScript file to be loaded.
You can try this:
var js:XML = <code><![CDATA[
function() {
window.myFunc = function(arg) {
alert(arg);
}
}
]]></code>;
ExternalInterface.call(js);
and later on you can safely call:
ExternalInterface.call("myFunc", "myArgument");
Note that using an xml is only a way to comfortably write the Javascript code (with indentation and multilines) ;)
FYI, alternately to using an XML Object you can call ExternalInterface on eval using a String containing JavaScript code.
var myJSCode:String = "window.log = function(msg) { if (console) console.log(msg) }"
ExternalInterface.call("eval", myJSCode);
And later call your function:
ExternalInterface.call("log", "Hello from ActionScript");
I'm developing a web page using jQuery, and I want it to execute some code only after ALL my JavaScript files are fully loaded. The head section of my HTML has the following script.
<script src="supervisor/lib/jquery-1.6.min.js" type="text/javascript"></script>
Inside jQuery file, I inserted the following code:
$.getScript('functions.js', function () {
// code here
});
The file functions.js has the following code:
$.getScript('mask.js');
$.getScript('validations.js');
$.getScript('lotsofscripts.js');
// and more...
I want the code here in the first $.getScript() to execute only after ALL the other JS are loaded, but this is not ocurring. What's the best way to achieve this?
PS: I'm using lots of $.getScript() because I find easier to separate them, but I want them to be inserted inside the same file.
You could always just increment a counter. That way your getScript calls remain asynchronous, as the last thing you want to do is change that. And frankly, any packaged solution you find to loading the scripts in parallel and then executing some function afterward will probably just be a shinier version of this:
var counter = 0;
var filesToLoad = ["mask.js", "validations.js", "lotsofscripts.js"];
var filesCount = filesToLoad.length;
// Increment counter each time a getScript completes
function incrementCounter() {
if (++counter === filesCount) {
// This code will execute after everything loads
}
}
// Iterate through the files and run getScript on them,
// with incrementCounter as the callback
for (var i = 0; i < filesCount; i++) {
$.getScript(filesToLoad[i], incrementCounter);
}
Here's a jsFiddle example.
Assuming you know the name of a function defined in a js script that needs to be tested for whether or not it has loaded...
I use Underscore.js isFunction() to figure this out ( http://documentcloud.github.com/underscore/#isFunction )
Example, if script.js contains a function myScriptFunction(), you can write a function that checks:
if (_.isFunction(myScriptFunction)) {
// script.js is loaded
// OK to move on to the next step
} else {
// script.js is not loaded
// check again later
}
I have tried binding to events to figure out if a js script file is loaded, but it doesn't seem to work across all the browsers.
I would suggest HeadJS to load your JS files. You can execute specific code upon completion of specific files or groups of files. Take a look, it's a great little project.
You might want to use jQuery.ajax() instead. You can set the async option to false (it's true by default when you use getScript