Is it possible to pass a javascript-variable to a script on another site?
I would like to do something like this:
This code is in a page on www.myfirstsite.net:
<script>
var ID = 'randomstring';
</script>
<script src="http://www.mysecondesite.net/processingscript.js"></script>
How can I read the var ID in the script on mysecondsite.net?
Update:
My question is wrong, as explained in the helpful answers from #vihan1086 and others.
Why to never do that
You should never declare variables like that, it has been described here
Then What?
On one page, do:
window.globals = {};
window.globals.my_variable = 'ABC';
On the script, add:
var globals = window.globals;
globals.my_variable;//Gets 'ABC'
This will keep all variables safe in a global place. Then we can get all global variables at once, increasing speed.
Don't forget to wrap all your code in something like:
(function() {
//Code here
})();
Functions
To make this easier I made functions:
setSharedVar (name, value) {
if (!"globals" in window) {
window.globals = {};
}
window.globals[name] = value;
}
getSharedVar (name) {
if (!"globals" in window) {
window.globals = {};
return null;
} else if (!name in window.globals) {
return null;
} else {
return window.globals[name];
}
}
Examples
Script 1:
setSharedVar('id', 5);
Script 2:
if (getSharedVar('id') === 5) {
alert('Success!');
}
Alerts 'Success!'
In your other script, ID will already exist and you can just use it.
Javascript runs in an environment attached to you web page, so as long a you dont change pages you can setup variable and includes other scripts that will have access to them.
So what you are proposing should work
However you should know that running script from other websites can be seen as dangerous and is therefore forbiden by some navigators/plugins ... so you should try and avoid it if possible (by providing a copy of the script on your website)
Related
Im building a webapp where i load the main page with its own javascript file in the index.html then the nav is calling all other pages in a div without a browser refresh using $.ajax and attaching specific script for each page in the div too with $.getScript.
Sometimes i needs to access a method declared in the main page javascript from within the div loaded javascript so what i generally do is attach the main method to document, exemple, instead of just:
let doThis = function(num){
// do your stuff
}
i do this
document.doThis = function(num){
// do your stuff
}
This way i can easily access it from any other javascript file loaded at different levels.
Thing is i feel its not a good practice, what would then be the good practice? or is it acceptable one?
If you are not using any bundler,then 'Revealing Module Pattern' can be used as a good practice here. This will allow the syntax to be more consistent and in this case, will make it easier to tell which of the functions can be accessed globally.
window.mainPageModule = (function () {
var privateVar = "abcd",
function privateFunction() {
//Do some private stuff here
}
function publicSetValue(value) {
privateVar = value;
}
function publicGetValue() {
return privateVar;
}
// Reveal desired functions to public
return {
doThis: publicSetValue,
getThis: publicGetValue
};
})();
Then, to access the public function anywhere globally
mainPageModule.doThis("1234")
Sorry for the noobish question, but nothing works for me today.
I'm creating a Phonegap application and have intergrated PushWoosh API into my app. And on receive push notification I want to run my previous functions again, so the data will be updated.
Pushwoosh has JS function like this:
document.addEventListener('push-notification',
function(event) {
var title = event.notification.title;
var userData = event.notification.userdata;
var notification = event.notification;
if (typeof(userData) != "undefined") {
console.warn('user data: ' + JSON.stringify(userData));
}
var object = JSON.parse(notification.u);
window.runPushFunctions(object.active, object.open); //Runs a jQuery function I have created..
}
);
Now window.runPushFunctions looks like this:
$(document).ready(function() {
window.runPushFunctions = function(active, open) {
if (active != null || active != undefined) {
$('.hubs-page').removeClass('hubs-active').hide().eq(active).show().addClass('hubs-active');
}
if (open == 2) {
$('html').addClass('hubs-opening');
}
//Trying to run functions from jQuery file that will get data from database and so on..
received();
sent();
checkFriends();
};
});
But I can't for some reason not run received(), sent(), checkFriends().
These functions is set like this in their own files like this:
(function($) {
'use strict';
function checkFriends () {
$.getJSON('url',function(data){
$.each(data,function(index,value){
//Do something with value
});
});
}
Im including files in this order:
file.js -> received(); sent();
file.js -> checkFriends();
file.js -> pushnotifications
Any help will be gladly appreciated
As the other answer here says, you are scoping your method definitions so they are not accessible anywhere outside the containing method.
(function($) {
This is a method definition. Any variables or functions non-globally declared within it cannot be accessed outside it. Therefore, you need to define the functions somewhere else or make them global for them to be accessible.
If you go for defining them somewhere else, you can simply move the function definitions to the top of the same file, outside of the (function($) {})() scope.
If you go for global definitions instead, you need to change the methods' defining lines slightly: instead of
function foo() { }
you need
window.foo = function() { }
This assigns an anonymously declared function to an object in the window scope, which is globally accessible. You can then call it using
window.foo();
or simply
foo();
since it is in the window scope.
I'm not exactly sure I'm understanding your question, but it looks to me like you are defining the function checkFriends inside of a function scope. If you need access to that function definition, you would need to declare it on an object that can be referenced from the global scope. Obviously the easiest way to do that would be to attach it to the window, though there are plenty of reasons not to do that.
window.checkFriends = function(){//code that does stuff};
I made a script that among other things has a function in it:
function updateGUI(){
document.getElementById("cursoft").value = getSoftware();
document.getElementById("curver").value = getCurrentVersion();
document.getElementById("rcycles").value = getResearchCycles();
document.getElementById("rcycle").value = getCurrentCycle();
document.getElementById("curproc").value = getCurrentProcess();
document.getElementById("curact").value = getCurrentAction();
}
The script runs on page load just fine, but when I try to run this function after the script finishes execution it's "undefined".
How can I make it "stay" in the current scope?
Tampermonkey scripts are run in a separate scope. This means that to make a function available globally you'll want to do something along the following:
window.updateGUI = function () {...}
If you want to add a number of functions to the global scope, it's better to store them under a single object and address your functions through there. That helps avoid any possible collisions you might otherwise have.
var myFunctions = window.myFunctions = {};
myFunctions.updateGUI = function () {...};
After that you can simply call myFunctions.updateGUI();.
A better way do to that is to grant unsafeWindow.
// #grant unsafeWindow
Then create your function like this:
function test()
{
console.log("test");
}
But also make it available in console through unsafeWindow:
if(!unsafeWindow.test)
{
unsafeWindow.test = test;
}
Then you can access test in the console.
I found an answer to my question, but Nit's answer is superior. I will still post mine in case someone needs it.
You can add functions to global scope by adding them to a script element and appending it to body
var scriptElem = document.createElement('script');
scriptElem.innerHTML = 'function updateGui() { /* stuff */ }';
document.body.appendChild(scriptElem);
var scriptElem = document.createElement('script');
scriptElem.innerHTML = 'function updateGui() { /* stuff */ }';
document.body.appendChild(scriptElem) Yes this works 100%
Hi,
I have my main file in which I include my javascript file.
In my javascript file I have this
$(document).ready(function(){
//some functions here
});
I want all the functions just available to this page and I know you can kinda conceal them to outside world of javascript by doing something like
(function(){
$document.ready(function(){
//my functions
)};
}).init();
but I am not 100% sure how would it be called or whether its even the right way.
Anyone shedding light on this would be a great help!
In javascript everything declared inside a function is only available inside that function (except for when you declare a variable without the keyword var).
So everything inside the function that you pass to $().ready() is only available inside that function.
$(document).ready(function () {
//all code here is scoped inside this function, so it can't be accessed
// outside of this function
});
Like the first comment says you can't hide them from the user, if they really want to see it, they will see it.
You can clean them up in a way if you really wanted to, something like
var mySpace = {};
mySpace.init = function() {
// your init functions here
};
in doc ready you just call
mySpace.init();
I am not sure if this is what you wanted but it is the way I understood the question
(function(){
var secret1 = function(msg) {console.log("Secret Message:" + msg);}
$document.ready(function(){
secret1("this can only be called from within");
)};
})();
secret1("this will cause a script error");
It sounds like the thing you are looking for is a 'javascript obfuscator'. Here is an example one. It makes the code much harder to read and copy. But as others have said, you can't actually fully hide javascript.
The problem here is that JavaScript is intrinsically a client-side scripting language unless using a server-side javascript application such as node.js.
As long as JavaScript is being used in this way, the entirety of your code will be downloaded much like downloading a .txt file from a website. The only real difference is that the ".js" extension and its inclusion in html <script> tags or in an AJAX call will force the user's browser to render it as JavaScript.
If you want to make the script a little harder for the user to find, however, this is doable. I recommend having your website retrieve the script via AJAX and appending it to the DOM. You can do this with require.js or by using Kickstrap and making your script into an "app." The script won't appear as a link in the DOM and the user would really have to search for it. You can make it even more difficult (without compromising the integrity of your site) by minifying the script. This will make it run faster while inadvertently making it less human-readable on the front end.
In JavaScript there is only function scope (the exception argument in try-catch being an exception). ES5 will let you use let (no pun intended) to achieve block scope but it wont be usefull untill majority of UAs implement it.
So your functions are concealed from the outside world, if with outside you mean outside the dom ready event.
$( document ).ready( function () {
var myFunc = function () {};
} );
myFunc();// <- ReferenceError: myFunc is not defined
You can't really hide the functions, as it's in the source code of a file downloaded by the client, but you can make it so they can't access your functions from javascript.
(function() {
var doStuff = function() {
// Not Accessible
console.log('You can\'t reach me!');
}
return {
'init': function() {
// Accessible
doStuff();
}
}
})().init();
If you are talking about Access Modifiers like public, private etc. Then check out this article on how Javascript handles this. Here are the key components:
//constructor function (class)
function Maths(x, y) {
//public properties
this.x =x;
this.y = y;
//public methods
this.add = function () { _sum = x + y; return _sum; }
this.mod = function () { _mod = x % y; return _mod; }
//public method calls private method
this.show = function () {
this.add();
this.mod();
showResult();
}
//private variables
var _sum=0;
var _mod=0;
//private methods
function showResult() {
alert( "sum: " + _sum + ", mod: " + _mod );
}
}
//end function
//create instance
var plus = new Maths(3, 4);
plus.show();
//static method multiply, you can use it without instance of Maths
Maths.multiply = function (x,y) { return x * y; }
//call static method by constructor function (class) without instance of Maths
var result = Maths.multiply(5,7);
alert(result);
//output: 35
I know. It is possible to dynamically load JavaScript and style sheet file into header of document. In the other hand, it is possible to remove script and style sheet tag from header of document. However, loaded JavaScript is still live in memory.
Is it possible to destroy loaded JavaScript from web browser memory? I think. It should be something like the following pseudo code.
// Scan all variables in loaded JavaScript file.
var loadedVariable = getLoadedVariable(JavaScriptFile);
for(var variable in loadedVariable)
{
variable = null;
}
// Do same thing with function.
Is it possible to create some JavaScript for doing like this?
Thanks,
PS. Now, you can use xLazyLoader and jQuery for dynamic loading content.
If the loaded script is assigned to a window property, for instance with the module pattern like so:
window.NiftyThing = (function() {
function doSomething() { ... }
return {
doSomething: doSomething
};
})();
or
window.NiftyThing = {
doSomething: function() { ... }
};
or
NiftyThing = {
doSomething: function() { ... }
};
Then you can delete the property that references it:
delete window.NiftyThing;
...which removes at least that one main reference to it; if there are other references to it, it may not get cleaned up.
If the var keyword has been used:
var NiftyThing = {
doSomething: function() { ... }
};
...then it's not a property and you can't use delete, so setting to undefined or null will break the reference:
NiftyThing = undefined;
You can hedge your bets:
NiftyThing = undefined;
try { delete NiftyThing; } catch (e) { }
In all cases, it's up to the JavaScript implementation to determine that there are no outstanding external references to the loaded script and clean up, but at least you're giving it the opportunity.
If, as Guffa says, the loaded script doesn't use the module pattern, then you need to apply these rules to all of its symbols. Which is yet another reason why the module pattern is a Good Thing(tm). ;-)
It might be possible to remove a Javascript file that has been loaded, but that doesn't undo what the code has done, i.e. the functions that was in the code are still defined.
You can remove a function definition by simply replacing it with something else:
myFunction = null;
This doesn't remove the identifier, but it's not a function any more.