Calling a javascript function in another javascript file without include - javascript

I have a question about javascript function flow. I am building a chrome extension where one javascript file creates a popup window using window.open. Based on the button selected in the popup, a variable is set and a function in the original javascript function should be called. But, it doesn't recognize that function from the original javascript file. I don't want to include file1 in file2's header, because other functions that I don't need would be called within file2. How do I handle this case?
A snippet of my code is the following:
in default_popup.html
<html
<head>
<script type="text/javascript" src="login.js"></script>
</head>
</html>
in login.js
function login() {
if (token === null) {
var url = chrome.extension.getURL('options.html');
window.open(url);
}
else {....}
function auth(url) {
............
}
//other functions here
in options.html
<html>
<head>
<script type="text/javascript" src="redirect.js"></script>
</head>
<body>
<button id="button1">Option1</button>
<button id="button2">Option2</button>
</body>
</html>
in redirect.js
var url;
document.getElementById('button1').onclick = function() {
url = 'url_one.com';
auth(url)
}
document.getElementById('button2').onclick = function() {
url = 'url_two.com';
auth(url);
}

Create a different JS file and you can call it common.js.
Transfer all the functions that needs to be accessed by both files there.

It is possible passing a function in the window reference, however chrome security setting may interfere that with local files because of the "same origin security principal", it works in other browsers on local, not sure in server pages and extension, so worth the test, follow the example:
html1:
<html>
<head>
<script type="text/javascript">
function test(){
var windowRef = window.open('test2.html');
windowRef['auth'] = function(){windowRef.document.write('property transferred')}
}//here you'll reference your auth function.
</script>
</head>
<body>
<input type="button" value="test" onclick="test()" >
</body>
</html>
html2:
<html>
<head>
<script type="text/javascript">
window['auth']() //the function to call, window.auth() should work too.
</script>
</head>
<body>
new window
</body>
</html>
The output will be a new window with "property transferred" in it.

Related

How to use constants across files? [duplicate]

A bunch of my JavaScript code is in an external file called helpers.js. Inside the HTML that calls this JavaScript code I find myself in need of knowing if a certain function from helpers.js has been called.
I have attempted to create a global variable by defining:
var myFunctionTag = true;
In global scope both in my HTML code and in helpers.js.
Heres what my html code looks like:
<html>
...
<script type='text/javascript' src='js/helpers.js'></script>
...
<script>
var myFunctionTag = false;
...
//I try to use myFunctionTag here but it is always false, even though it has been se t to 'true' in helpers.js
</script>
Is what I am trying to do even feasible?
You need to declare the variable before you include the helpers.js file. Simply create a script tag above the include for helpers.js and define it there.
<script type='text/javascript' >
var myFunctionTag = false;
</script>
<script type='text/javascript' src='js/helpers.js'></script>
...
<script type='text/javascript' >
// rest of your code, which may depend on helpers.js
</script>
The variable can be declared in the .js file and simply referenced in the HTML file.
My version of helpers.js:
var myFunctionWasCalled = false;
function doFoo()
{
if (!myFunctionWasCalled) {
alert("doFoo called for the very first time!");
myFunctionWasCalled = true;
}
else {
alert("doFoo called again");
}
}
And a page to test it:
<html>
<head>
<title>Test Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="helpers.js"></script>
</head>
<body>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
<script type="text/javascript">doFoo();</script>
<p>Some stuff in between</p>
<script type="text/javascript">doFoo();</script>
<p>myFunctionWasCalled is
<script type="text/javascript">document.write(myFunctionWasCalled);</script>
</p>
</body>
</html>
You'll see the test alert() will display two different things, and the value written to the page will be different the second time.
OK, guys, here's my little test too. I had a similar problem, so I decided to test out 3 situations:
One HTML file, one external JS file... does it work at all - can functions communicate via a global var?
Two HTML files, one external JS file, one browser, two tabs: will they interfere via the global var?
One HTML file, open by 2 browsers, will it work and will they interfere?
All the results were as expected.
It works. Functions f1() and f2() communicate via global var (var is in the external JS file, not in HTML file).
They do not interfere. Apparently distinct copies of JS file have been made for each browser tab, each HTML page.
All works independently, as expected.
Instead of browsing tutorials, I found it easier to try it out, so I did. My conclusion: whenever you include an external JS file in your HTML page, the contents of the external JS gets "copy/pasted" into your HTML page before the page is rendered. Or into your PHP page if you will. Please correct me if I'm wrong here. Thanx.
My example files follow:
EXTERNAL JS:
var global = 0;
function f1()
{
alert('fired: f1');
global = 1;
alert('global changed to 1');
}
function f2()
{
alert('fired f2');
alert('value of global: '+global);
}
HTML 1:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
HTML 2
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="external.js"></script>
<title>External JS Globals - index2.php</title>
</head>
<body>
<button type="button" id="button1" onclick="f1();"> fire f1 </button>
<br />
<button type="button" id="button2" onclick="f2();"> fire f2 </button>
<br />
</body>
</html>
Hi to pass values from one js file to another js file we can use Local storage concept
<body>
<script src="two.js"></script>
<script src="three.js"></script>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>
</body>
Two.js file
function myFunction() {
var test =localStorage.name;
alert(test);
}
Three.js File
localStorage.name = 1;
//Javascript file 1
localStorage.setItem('Data',10);
//Javascript file 2
var number=localStorage.getItem('Data');
Don't forget to link your JS files in html :)
If you're using node:
Create file to declare value, say it's called values.js:
export let someValues = {
value1: 0
}
Then just import it as needed at the top of each file it's used in (e.g., file.js):
import { someValues } from './values'
console.log(someValues);
I think you should be using "local storage" rather than global variables.
If you are concerned that "local storage" may not be supported in very old browsers, consider using an existing plug-in which checks the availability of "local storage" and uses other methods if it isn't available.
I used http://www.jstorage.info/ and I'm happy with it so far.
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
You can set
window['yourVariableName'] = yourVariable;
and it will make that variable global for all the files.

Loading AJAX response without DIV

I have a jsp calling AJAX response of which contains script tag
<script>
var globalvar =
var globalvar2 =
</script>
I load the response to a DIV element. However, any variables defined in script tag of DIV are not accessible in other script tags in the body of jsp.
Can someone suggest how to get the script from AJAX response accessible to other script on the page?
I Think you have a timing problem.
a better way to store your variables is in a hidden input field.
<input type="hidden" id="foobar" value="test">
<script>
var myVariable = document.getElementByID('foobar').value; // to get
document.getElementByID('foobar').value = 'test' // to set
It depends on the ordering of your JS scripts. If you're declaring those vars below a script that needs access to them, they will not be available. Take this scenario for example.
<html>
<head>
<script type='text/javascript' src='js/jsFunctions.js'></script>
</head>
<body>
<script type='text/javascript'>
var globalvar = "test";
</script>
<body>
</html>
If you call a function in jsFunctions.js and try to use the globalvar variable, it won't work. Instead, it needs to be created above any script which you need access within the document.
<html>
<head>
<script type='text/javascript'>
var globalvar = "test";
</script>
<script type='text/javascript' src='js/jsFunctions.js'></script>
</head>
<body>
<body>
</html>

Including .asp that contains JavaScript code

I have two files A.asp and B.asp . The B.asp contains long javascript function that i want to use in A.asp. To include it, i used:
<!--#include file="lib/B/B.asp"-->
...in the head of A.asp I added:
<script>
function use(){
try{
test = new FPDF();
}catch(err){
document.write(err);
}
}
new FPDF() is an object reference to function FPDF() in B.asp file that looks like this:
<script>
function FPDF(){
var x;
this.x = function x(){
...
}
}
</script>
I get an error message: "ReferenceError: FPDF is not defined"... How can i properly do this?
What i want to do is to call the function in FPDF() like this:
<script>
function use(){
try{
test = new FPDF();
test.x(); //!!!!
}catch(err){
document.write(err);
}
}
Create an external javascript file like (myscript.js) and keep all your javascript code there.In a.asp reference that javascript file similary in b.asp reference the same javascript file.
Example --- in a.asp
<html>
<head></head>
<body>
<script src="/myscript.js"></script>
</body>
</html>
Simiraly in b.asp-----
<html>
<head></head>
<body>
<script src="/myscript.js"></script>
</body>
</html>
The "runat=server" instruction does precisely that, it tells the server to execute the code rather than serve it as is for the web browser to interpret. To give you a very simple example:
<html>
<head>
<script language="Jscript" runat="server">
var helloworld = "Hello World";
</script>
</head>
<body>
<%= helloworld %>
</body>
</html>
When this page is requested the server will send the following to the browser
<html>
<head>
</head>
<body>
Hello World
</body>
</html>
So the reason your onclick button doesn't work is that there's no JS on the page which it can see. If you want to send variables to a server side function then you'll need to post them to the page in a form and then use Request.Form to retrieve them.
I hope this helps

Can I communicate between two local html files using javascript?

I have two local .html files in the same folder. One page opens a window with the other page, and attempts to call a function in the newly opened window. However, the function call fails, and I get this in the console:
Unsafe JavaScript attempt to access frame with URL file:///***/A.html from frame with URL file:///***/B.html. Domains, protocols and ports must match.
This happens on both Chrome and Webkit (Mac). Is there any way I can either: disable the cross-domain checks for the file:// protocol, or call a javascript function in a different local file?
You can use window.postMessage to do something like this:
The initial window html file:
<!DOCTYPE html>
<html>
<head>
<script>
var otherWindow;
function openOther() {
otherWindow = window.open("other.html", "otherWindow");
}
function otherFunc() {
otherWindow.postMessage("otherFunc", "*");
}
</script>
</head>
<body>
<div onclick="openOther()">Open the other window</div>
<div onclick="otherFunc()">Call the other window's function</div>
</body>
</html>
Html for the second window:
<!DOCTYPE html>
<html>
<head>
<script>
window.addEventListener("message", function(event) {
alert("The other window's function executed.");
}, false);
</script>
</head>
<body>
<div>This is the other window.</div>
</body>
</html>
Here's a good reference for window.postMessage.

Access JavaScript function in a programatically iFrame

I am trying to access a JavaScript function in a programatically created iFrame from a JavaScript function outside. I tried several ways, but was not successful. L ike window.frames['frameid'], etc.
Could you please provide me the correct syntax?
Yes, they are in the same domain. Actually, I am using ExtJS framework. I have a JSP inside an iFrame, I would like to call the javascript functions in the JSP from the a javascript function outside which is basically in a JS file.
Here's a more appropriate example based on your comments ;)
The main page
<html>
<head>
<title>Main Page</title>
</head>
<body>
<iframe src="iframe.html"></iframe>
<script>
var receiver = {
listen:function(msg){
alert(msg);
}
};
</script>
</body>
</html>
The iframe page: iframe.html, but can be a JSP with similar output
<html>
<head>
<title>iframe page</title>
<script src="external.js"></script>
</head>
<body>
<!-- some content here -->
<script>
externalFunction('hello', window);
</script>
</body>
</html>
And the JS file: external.js
function externalFunction(msg, w){
w.parent.receiver.listen(msg);
}
Place those 3 files in the same directory and open the main page.
You should get a popup with "hello".

Categories

Resources