TideSDK: Is there a way to pass data to a child window? - javascript

When I create a child window from my main window, I'd like to pass a JavaScript object ot it, but I'm not sure if there actually is a way to do it?
Two windows created with TideSDK each have their own JavaScript environement, just like two browser windows (and that's just what they are, If I understand it right), so you can't access a variable in one window from another one. On the other hand, you can access other windows from the one you are in (for example with Ti.UI.getOpenWindows). So... is there a way to do it?
There are some workarounds I believe are possible, but none of them is very straightforward, and each uses something other then just plain JavaScript:
using Ti.Database or Ti.Filesystem to store the data I want to pass, and then retrieve it from the child window
pass the data to the new window as GET variables,example: Ti.UI.createWindow("app://page.html?data1=test&data2=foobar");

you can assign the object to the child window object
var objToBePassed = {foo:'bar'};
var currentWindow = Ti.UI.currentWindow;
var newWindow = currentWindow.createWindow("app://page.html");
newWindow.obj = objToBePassed;
newWindow.open();
and in the javascript environment of the child window you can access the object by
var currentWindow = Ti.UI.currentWindow;
var obj = currentWindow.obj;
another way is to use Ti.API.set:
Ti.API.set('objKey', objToBePassed);
and you can access the object anywhere by
var obj = Ti.API.get('objKey');

I know this has been answered, but I came accross a way to mimic the PHP $_GET variable, which will do what the OP asked I reckon:
<script type="text/javascript">
(function(){
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
})();
</script>
And then use it:
<script type="text/javascript">
var conts = '<li><a title="back to list" href="/menu.html?module='+document.$_GET['module']+'">Unit Listing</a></li>';
document.write(conts);
</script>
Works fo me.

Related

how to use one function variable in another function in javascript

I want to access one function variable in another function,
My first function and variable
var max;
papaya.viewer.Viewer.prototype.pagination = function () {
var max = this.volume.header.imageDimensions.zDim;
}
My second function
papaya.Container.fillContainerHTML = function(){
// I want to access max value here
}
I want to access the max value to a second function,
I tried many ways to do but I can't able to make it.
Just declare max as a global variable, outside the functions, where it can be accessed by both, like so:
var max;
papaya.viewer.Viewer.prototype.pagination = function () {
max = this.volume.header.imageDimensions.zDim;
}
papaya.Container.fillContainerHTML = function(){
// You can now access max value here
}
If it doesn't work, send an online demo so we can help.
You can return this value and get from fillContainerHTML
papaya.viewer.Viewer.prototype.pagination = function () {
return this.volume.header.imageDimensions.zDim;
}
papaya.Container.fillContainerHTML = function(){
var view = new papaya.viewer.Viewer();
var a = view.pagination();
console.log(a);
}
The Best and easiest solution to your question
Hi. I had researched a lot about the question you are asking. I watched many tutorials, but they were really complicated. So once, I was working on a project. I didn't realise, but I used a variable created/edited in a function in another function. It was really simple. You need to create Local Storage to do this. The localStorage and sessionStorage properties allow to save key/value pairs in a web browser. It is Supported in almost every famous or known web browser like Google Chrome, Firefox, Opera, safari, Microsoft Edge etc.
Note: if you click Run code snippet button, the code won't work because Stack Overflow doesn't support Local Storage. So, go to another text editor like notepad, run the code, and see the result on any Browser (mentioned above). It will work.
// Creates a variable
var max = "Nothing";
function btn1() {
// Makes a change to max variable
var max = "Max variable changed";
// Creates Local Storage on browser
var setLocalStorage = localStorage.setItem("max", max);
}
function btn2() {
var getLocalStorage = localStorage.getItem("max");
document.ById("text").innerHTML = getLocalStorage;
}
<html>
<body>
<p id="text"> Nothing </p>
<button onclick="btn1()"> Make change </button>
<button onclick="btn2()"> See change </button>
</body>
</html>

Overriding native methods and objects INSIDE a particular object

I'm trying to override a native method called "localStorage" for functions INSIDE an object.
Here's a gist of what I'm trying to do:
function SomeObject(){
this.localStorage = "aaa"; //block access to localStorage for functions INSIDE this object.
... (some more code here)
_testRun(){
window.testA = localStorage; //chose to store the instance on a window (global-like) object
}
this.testRun = function(){ _testRun(); };
this.testRun2 = function(){ window.testB = localStorage;};v
}
var a = new SomeObject();
a.testRun();
a.testRun2();
(after this, when I look up window.testA and window.testB, they both point to the Native localStorage, not the custom one inside the SomeObject.)
BTW, I don't want to override a native function for the whole document.
(i.e. might use native localStorage OUTSIDE the object)
Any suggestions/solutions on how I can do this? thanks!
Try to add window.localStorage and this.localStorage instead of just localStorage
function SomeObject(){
this.localStorage = "aaa"; //block access to localStorage for functions INSIDE this object.
... (some more code here)
_testRun(){
window.testA = window.localStorage; //chose to store the instance on a window (global-like) object
}
this.testRun = function(){ _testRun(); };
this.testRun2 = function(){ window.testB = this.localStorage;};
}

copying data from one page to another using phantomJS

I am trying to copy some data from one processed web page into a new one that I want to export. The background is that I need to scrape parts of a page and need to build a new page with parts of the original page.
The problem seems that phantomJs includeJs() and evaluate() methods are sandboxed and I can't see a proper way to import DOM from one page to another.
I have some test code that looks like this, with page being the original and out the new page:
....
var title = page.evaluate(function() {
return title = document.getElementById('fooo').innerHTML;
});
console.log('page title:' + title);
//fs.write('c:/Temp/title.js', "var title = '" + title + "';", 'w');
var out = new WebPage;
out.viewportSize = page.viewportSize;
out.content = '<html><head></head><body><div id="wrapper"></div><p>done</p></body></html>';
out.includeJs('c:/Temp/title.js', function() {
var p = document.createElement('p');
p.appendChild(document.createTextNode(title));
document.getElementById('wrapper').appendChild(p);
});
...
The function in your last includeJs call here won't work - as you note, it's sandboxed, and that means that closures won't work, so title won't be defined. A method of passing variables to page.evaluate is noted as a feature request, but isn't available as of PhantomJS v.1.4.1.
The general way I get around this is by using the Function constructor, which allows you to create a function using a string:
var myVar = {some:"values", I:"want to pass into my page"},
test = new Function("window.myVar = " + JSON.stringify(myVar));
page.evaluate(test);
Now you can evaluate a function like the one you have, referencing myVar in the sandbox, and your data will be available in the client scope.

Extract all links from a string

I have a javascript variable containing the HTML source code of a page (not the source of the current page), I need to extract all links from this variable.
Any clues as to what's the best way of doing this?
Is it possible to create a DOM for the HTML in the variable and then walk that?
I don't know if this is the recommended way, but it works: (JavaScript only)
var rawHTML = '<html><body>barzort</body></html>';
var doc = document.createElement("html");
doc.innerHTML = rawHTML;
var links = doc.getElementsByTagName("a")
var urls = [];
for (var i=0; i<links.length; i++) {
urls.push(links[i].getAttribute("href"));
}
alert(urls)
If you're using jQuery, you can really easily I believe:
var doc = $(rawHTML);
var links = $('a', doc);
http://docs.jquery.com/Core/jQuery#htmlownerDocument
This is useful esepcially if you need to replace links...
var linkReg = /(<[Aa]\s(.*)<\/[Aa]>)/g;
var linksInText = text.match(linkReg);
If you're running Firefox YES YOU CAN ! It's called DOMParser , check it out:
DOMParser is mainly useful for applications and extensions based on Mozilla platform. While it's available to web pages, it's not part of any standard and level of support in other browsers is unknown.
If you are running outside a browser context and don't want to pull a HTML parser dependency, here's a naive approach:
var html = `
<html><body>
Example
<p>text</p>
<a download href='./doc.pdf'>Download</a>
</body></html>`
var anchors = /<a\s[^>]*?href=(["']?)([^\s]+?)\1[^>]*?>/ig;
var links = [];
html.replace(anchors, function (_anchor, _quote, url) {
links.push(url);
});
console.log(links);

Nested Objects With YUI and Javascript

I am working on a Javascript object that contains some YUI objects. The key thing is, my object needs to contain it's own set of YUI tabs so that I can display multiple instances of my object on the same page and have the tabs control their own object instance.
I set it up as follows:
var Scheduler = function(divid,startDate,mode){
this.tabView = null;
...
this.init = function(){
this.tabView.appendTo(this.calendar_cell);
this.tabView.addTab( new YAHOO.widget.Tab({
label: 'Day',
content:'<div id="'+ this.calendar_day_div +'" style="width:100%; height:auto;"></div>'
}));
var tab0 = this.tabView.getTab(0);
tab0.addListener('click', this.showWeek);
}
this.showWeek(){
alert(this);
}
});
Here's the problem. I would expect the alert(this); in this.showWeek to alert the instance of scheduler. Instead, it's giving me the tab li. I tried alerting this.parent and am given 'undefined' as an answer.
How should I set this up to do what I need to do?
The addListenter method takes a scope argument. So you can change your call to the following to solve your problem (since you are using YUI):
tab0.addListener('click', this.showWeek, undefined, this);
When you attach a function to an event of an object (in this case the object held by tab0) then its usually that object that becomes the this context of the function when it executes.
Adjust your code like this:-
var self = this;
this.showWeek(){
alert(self);
}

Categories