One main JS varibles file for multiple HTML files - javascript

So I am wanting to create one file where I can list and edit links without opening every file.
So I am wanting to have a page like http://example.com/links.js and in there I want to have all my information where I can information.
I will have around 20 http://example.com/link1.html etc. So instead of opening every HTML file to edit it, I would like to have just one main file where I can set for example links and titles.
I am not perfect at JS but I do understand the most parts. So in the jar file I will have like "var link1 = www.google.com" and inside link1.html, it will turn out as <a href="www.google.com></a> Something like that.
Sorry if you do not understand this as I am tired and cannot explain correctly. Thanks.

I managed to find a way to do this by using :)
link3 = function() {
location.href = "http://google.com";
}

Though it is a broad topic but hopefully this will help you in designing your application.
You can have one js file will a json object. Example
links.js
var Links = {}; // namespacing
Links.linkObject = {
linkOne:"someLink",
linkTwo:"someLinkTwo",
//Rest of links
}
Links.linkContains() {
return Links.linkObject;
}
Import this file using script tag
<script src="links.js"></script>
Now in your main js file or any other file you can call this inside some function
function customFunction() {
var getLinks = Links.linkContains() // will return the json array of links
}
Once you get the getLinks you can use dot or bracket notation to get the value.
For example getLinks.linkOne will return someLink.
You can use this object to retrieve value anywhere in your application and when you will change the relevant value in link.js it will reflect everywhere

Related

Sharing Data Between Javascript Files

I have a script that generates a JSON formatted string. I want to use the data contained in this string in another script. I'm not sure where to even start. I've thought about running both scripts from the same directory and somehow outputting the JSON data into a text file and then loading it into the second script but this seems like more of a workaround than an actual solution. Is it possible to somehow call the second script from the first and pass it the data? Much like passing data between functions in a single script?
FWIW I have tried simply combining the functions the two scripts perform into one, but this has caused me countless headaches with no progress. For simplicity sake I'd prefer to keep the functions performed by each script separate (apart from the obvious data sharing requirement!).
Any advice or a point in the right direction would be greatly appreciated.
If JSON data is less than 5 mb then you can use localStorage to save the output in browser.
In first js file:
function fOne(){
var jsonStr = ''; //insert some json data here
localStorage.setItem("myJson", JSON.stringify(jsonStr)); //save data
}
In your second js file:
function fTwo(){
if (localStorage.getItem("myJson") !== null) {
var passedJson = localStorage.getItem("myJson"); //get saved data anytime
}
}
It is hard to say without some code to reference but maybe just a global variable with a check if its null.
var myJsonString = null;
function one () {
var jsonString = "[]";
myJsonString = jsonString;
}
function two () {
//string not set so bail
if (myJsonString === null) { return; }
}
So it actually depends what environment you are programming in. If its a web browser, all of the code is in the global space actually and is run in order. so if you have <script src="file1"> then <script src="file2"> in your html file, and you put x = 10 in the first file and use it in the second, you will have no problems. If you are using node.js, I can post a solution for that as well, just let me know.
(btw if you put x = 10 in the second file and reference it from the first it will throw an error)
There are ways of avoiding this, such as using a document.ready function or wrapping things in functions and then calling them at the end. You need to make sure that functions and variables are created before being used (this is a common mistake beginners make and are confused by)

How to get data from file in the same folder as a JS variable in a background page?

So my question is this: i have a box.html that contains some <div>s. It is way too big to be stored as a string in the background script. It would be very inconvenient to change anything in the html if it was stored as just a string variable.
What I can't figure out is how to access that file from background.js so that all of the html is then stored in a variable like var box = "some html"
So that when I have that variable I can then pass it on to a content script when I need it.
I know that chrome.extension.getURL('box.html'); gets the path to the file I need, but how do I load the file?
in Firefox this is simply done with: self.data.load('box.html'); in the main.js
so is there a similar call for google chrome?
I've used a simple ajax request through jQuery to solve this in the past:
var myDiv = document.queryElement('my_div');
$.get(chrome.extension.getURL('box.html'), function(data) {
myDiv.innerHTML = data;
});

Is there a way to crawl a site and grab JavaScript variables on each page?

The company I work for is going to be going through a site redesign in a few months, and one of the things we need is a table containing every URL of every page on the site. Then, optimally, there would be columns containing the values of a set of predefined JavaScript variables (in this case, Omniture variables, so we can ensure each page is properly tagged with its place in the site hierarchy).
Here's an example of what might be in the HTML for a given page:
<script type="text/javascript">
metrics_level2 = "biz";
metrics_level3 = "products";
metrics_level4 = "my_awesome_product";
metrics_pagename = "biz|products|my_awesome_product";
</script>
I've crawled the site with RapidMiner and the data is ready to go, but my issue is the best way to isolate these variables and put "metrics_level2", "metrics_level3", etc. in their own columns. Is XPath the best way to do it? Regular expressions? My attempts with XPath seem to bring in the entire contents between the tags, which requires a lot of cleaning up after the fact.
If you use PhantomJS http://phantomjs.org/ you can simply access these variables as you would from within the webpage, with JavaScript. A very simple example is as follows:
//where url is the page that contains these variables.
page.open(url, function (status) {
//Page is loaded!
var dataFromPage = page.evaluate(function(){
return {
metrics_level2:metrics_level2,
metrics_level3:metrics_level3,
metrics_level4:metrics_level4
};
});
//dataFromPage now contains those variables
phantom.exit();
});
If you already have your webpages scraped and saved off to html files or something, you could just set the content of the page object using the content method as appose to opening the page as seen above. See http://phantomjs.org/api/webpage/property/content.html

Store very small amount of data with javascript

I have one of those websites that basically gives you a yes or no response to a question posed by the url. An example being http://isnatesilverawitch.com.
My site is more of an in-joke and the answer changes frequently. What I would like to be able to do is store a short one or two word string and be able to change it without editing the source on my site if that is possible using only javascript. I don't want to set up an entire database just to hold a single string.
Is there a way to write to a file without too much trouble, or possibly a web service designed to retrieve and change a single string that I could use to power such a site? I know it's a strange question, but the people in my office will definitely get a kick out of it. I am even considering building a mobile app to manipulate the answer on the fly.
ADDITIONAL:
To be clear I just want to change the value of a single string but I can't just use a random answer. Without being specific, think of it as a site that states if the doctor is IN or OUT, but I don't want it to spit out a random answer, it needs to say IN when he is IN and OUT when he is out. I will change this value manually, but I would like to make the process simple and something I can do on a mobile device. I can't really edit source (nor do I want to) from a phone.
If I understand correctly you want a simple text file that you change a simple string value in and have it appear someplace on your site.
var string = "loading;"
$.get('filename.txt',function(result){
string = result;
// use string
})
Since you don't want to have server-side code or a database, one option is to have javascript retrieve values from a Google Spreadsheet. Tabletop (http://builtbybalance.com/Tabletop/) is one library designed to let you do this. You simply make a public Google Spreadsheet and enable "Publish to web", which gives you a public URL. Here's a simplified version of the code you'd then use on your site:
function init() {
Tabletop.init( { url: your_public_spreadshseet_url,
callback: function (data) {
console.log(data);
},
simpleSheet: true } )
}
Two ideas for you:
1) Using only JavaScript, generate the value randomly (or perhaps based on a schedule, which you can hard code ahead of time once and the script will take care of the changes over time).
2) Using Javascript and a server-side script, you can change the value on the fly.
Use JavaScript to make an AJAX request to a text file that contains the value. Shanimal's answer gives you the code to achieve that.
To change the value on the fly you'll need another server-side script that writes the value to some sort of data store (your text file in this case). I'm not sure what server-side scripting (e.g. PHP, Perl, ASP, Python) runtime you have on your web server, but I could help you out with the code for PHP where you could change the value by pointing to http://yoursite.com/changeValue.php?Probably in a browser. The PHP script would simply write Probably to the text file.
Though javascript solution is possible it is discouraged. PHP is designed to do such things like changing pieces of sites randomly. Assuming you know that, I will jump to javascript solution.
Because you want to store word variation in a text file, you will need to download this file using AJAX or store it in .js file using array or string.
Then you will want to change the words. Using AJAX will make it possible to change the words while page is loaded (so they may, but do not have to, change in front of viewers eyes).
Changing page HTML
Possible way of changing (words are in array):
wordlist.js
var status = "IN"; //Edit IN to OUT whenever you want
index.html
<script src="wordlist.js"></script>
<div>Doctor is <span id="changing">IN</span></div>
<script>
function changeWord(s) { //Change to anything
document.getElementById("changing").innerHTML = s;
}
changeWord(status); //Get the status defined in wordlist.js
</script>
Reloading from server
If you want to change answer dynamically and have the change effect visible on all open pages, you will need AJAX or you will have to make browser reload the word list, as following:
Reloading script
function reloadWords() {
var script = document.createElement("script"); //Create <script>
script.type="text/javascript";
script.src = "wordlist.js"; //Set the path
script.onload = function() {changeWord(status)}; //Change answer after loading
document.getElementsByTagName("head")[0].appendChild(script); //Append to <head> so it loads as script. Can be appended anywhere, but I like to use <head>
}
Using AJAX
Here we assume use of text file. Simplest solution I guess. With AJAX it looks much like this:
http = ActiveXObject==null?(new XMLHttpRequest()):(new ActiveXObject("Microsoft.XMLHTTP"));
http.onloadend = function() {
document.getElementById("changing").innerHTML = this.responseText; //Set the new response, "IN" or "OUT"
}
http.open("GET", "words.txt")
http.send();
Performance of AJAX call may be improved using long-poling. I will not introduce this feature more here, unless someone is interested.

Managing Html text in popup

I'm using OpenLayer popup.
when initializing it, there a parameter required to contain the html displayed in the popup.
this parameter is javascript string.
I have a conflict, on the one hand the html text is long so I prefer to place it in html file and read the file to the variable.
On the other hand, the html depends on other local variables, so if I leave it on its place I can concatenate some strings and local variables to compose the final variable containing the html text. but it is very long and ugly code...
Maybe experienced javascript programmers can help me to find a design solution to this problem?
thanks
As you are using OpenLayers you can use the OpenLayers.loadURL function to retrieve HTML from your server.
http://dev.openlayers.org/releases/OpenLayers-2.10/doc/apidocs/files/OpenLayers/Ajax-js.html
If you want to pass in local variables to server side HTML you can set up a simple handler that accepts variables, and integrates these into some static HTML (using string formatting or a template).
If you are using .NET then a .ashx file can do this. See http://dotnetperls.com/ashx for an example.
Another solution is to use an Ajax request to load your file, and then print the content inside the popup.
Using JQuery:
$.get('myfile.php',function(content){
var popup = new OpenLayers.Popup("popupid",
new OpenLayers.LonLat(mouseX,mouseY),
new OpenLayers.Size(360,200),
content,
true);
map.addPopup(popup);
});
When the Ajax request is completed, you can create the popup and fill it with the file content previously loaded.
I would recommend geographikas solution, and also try to use different js-classes to improve maintainability and readability. Don't do everything in the same object, make your own popup object that inherits from or uses OpenLayers.Popup.Anchored or something, and make the Ajax server call from there. This way you won't clutter your other code with this. Also makes it easy to reuse and substitute when needed.
I would go for something like this (untested!):
mynamespace.mypopup = function(o) {
var size = new OpenLayer.Size(100, 70);
var icon = new OpenLayers.Icon(); // Fill it
var popup = new OpenLayers.Popup.Anchored(o.id, o.lonlat, size, getContent(), icon, false, null);
var getContent = function() {
// ajax call
// return a string
}
return popup;
}
in a file called "mypopup.js"
and call it with:
var popup = new mynamespace.mypopup({id: 'whatever', lonlat: myLonLat});

Categories

Resources