I have a javascript code which is connected to a htlm called "old.html". I do thing in there and then I have another html called "new.html" in which I want to add html elements in there.
I have this code in which I try to assign the div q1 to the variable myVar.
var printWindow = window.open("http://10.180.101.58:5500/new.html", 'Print');
var myVar = printWindow.document.getElementById('q1');
my html looks like this:
<body>
<form>
<div id="q1"></div>
</form>
<script src="DemoCode.js"></script>
</body>
These 2 files are in the same directory, but I think the problem is with the window.open()
I can't do document.getElementById() because I also have the "old.html" which let's say is the original html connected to my javascript and whenever I call document.getElementById() it gets elements from that one.
Does anyone know any way so that I can get elements from "new.html""?
I am using <script src="DemoCode.js"></script> in both html's so I can say that both are connected to my javaScript.
There are two answers here:
If the window where the code doing this is on the same origin (http://10.180.101.58:5500),
you have to wait for the DOM to be loaded in the new window (for instance, using the DOMContentLoaded event) before you can access it.
If the window where the code doing this isn't on the same origin as the new window you're opening, then you can't access its DOM, since of course that would be a massive security hole.
Here's how you'd do it in case #1:
const printWindow = window.open("http://10.180.101.58:5500/new.html", "Print");
printWindow.addEventListener("DOMContentLoaded", () => {
const myVar = printWindow.document.getElementById("q1");
// ...use it here...
});
I am using <script src="DemoCode.js"></script> in both html's so I can say that both are connected to my javaScript.
That doesn't in any way connect the windows (imagine all the windows that would be connected by jQuery or React loaded from a CDN!). All it does is load the code in that file into both windows.
Related
<textarea name="widget-generalcode" cols="50" rows="13" id="widget-generalcode"></textarea>
and javascript
<script>
document.getElementById('widget-generalcode').innnerHTML = 'test';
</script>
When I run code, error TypeError: document.getElementById(...) is null, how to fix it ?
May be you should put it on pageload:
<script type="text/javascript">
window.onload = function(){
document.getElementById('widget-generalcode').innerHTML = 'test';
};
</script>
You should consider where you place javascript statements.
It will effect to the desired result.
I recommended that you should use web development tool such as Firebug in Firefox (press F12)
It will help you to debug javascript code and you can use Timeline feature to detect which parts of your Html/javascript "spent" a lot of resources.
Hope this information is useful.
First of all, check that your JavaScript is executed when DOM is loaded. One option is to put your <script> tag just before </body>.
Then, you should use value property for form fields:
document.getElementById("widget-generalcode").value = "test";
you are trying to access the element before it is rendered on your page so you will never get that element so write your code in function as below
<script>
function call()
{
document.getElementById('widget-generalcode').value = 'test';
}
</script>
and now in body tag palce onload ="call()" as given below it will work
<body onload ="call()" >
</body>
Sorry I'm new 2 Stackoverflow
In asp.net Actualy Startup is my id but on clientside it will be displayed as ctl00_dmrcontent_Startup
so in ur script change id form widget-generalcode to what display in clientside
<div id="Startup" runat="server">
This caused me much grief. It's a matter of understanding the sequence of execution of the "onLoad" (which occurs after all the PHP has been executed and turned into HTML), and the running of a js command after say parsing the url parameters (which occurs before onLoad).
The javascript function ran before the html page with rendered by the browser. So the element with the id="widget-generalcode" did not exist when the code ran.
Use window.unload= functionName at the top of your javscript file, without parentheses (). This tells the browser to run the function after the html page loads. This way the html element will exist when the function runs and the javascript can act on it.
Is it possible to hide the Javascript code from the html of a webpage, when the source code is viewed through the browsers View Source feature?
I know it is possible to obfuscate the code, but I would prefer it being hidden from the view source feature.
I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.
As other have said, there is no way to protect JavaScript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your JavaScript in an external JavaScript file that is included with:
<script type="text/javascript" src="http://mydomain.example/xxxx.js"></script>
tags, then the JavaScript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external JavaScript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
Put it in an external .js file.
Obfuscate the file so that most native variable names are replaced with short versions, so that all unneeded whitespace is removed, so it can't be read without further processing, etc...
Dynamically include the .js file by programmatically adding script tags (like Google Analytics does). This will make it even more difficult to get to the source code from the View Source command as there will be no easy link to click on there.
Put as much interesting logic that you want to protect on the server that you retrieve via AJAX calls rather than do local processing.
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at what you do, not by having secrets. That's ultimately how success works on the web anyway.
No, it isn't possible.
If you don't give it to the browser, then the browser doesn't have it.
If you do, then it (or an easily followed reference to it) forms part of the source.
My solution is inspired from the last comment. This is the code of invisible.html
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>
The clear code of invisible_debut.js is:
$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});
Notice that at the end I'm removing the created script.
invisible.js is:
$(document).ready(function(){
alert('try to find in the source the js script which did this alert!');
document.write('It disappeared, my dear!');});
invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.
Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.
Use Html Encrypter The part of the Head which has
<link rel="stylesheet" href="styles/css.css" type="text/css" media="screen" />
<script type="text/javascript" src="script/js.js" language="javascript"></script>
copy and paste it to HTML Encrypter and the Result will goes like this
and paste it the location where you cut the above sample
<Script Language='Javascript'>
<!-- HTML Encryption provided by iWEBTOOL.com -->
<!--
document.write(unescape('%3C%6C%69%6E%6B%20%72%65%6C%3D%22%73%74%79%6C%65%73%68%65%65%74%22%20%68%72%65%66%3D%22%73%74%79%6C%65%73%2F%63%73%73%2E%63%73%73%22%20%74%79%70%65%3D%22%74%65%78%74%2F%63%73%73%22%20%6D%65%64%69%61%3D%22%73%63%72%65%65%6E%22%20%2F%3E%0A%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%20%73%72%63%3D%22%73%63%72%69%70%74%2F%6A%73%2E%6A%73%22%20%6C%61%6E%67%75%61%67%65%3D%22%6A%61%76%61%73%63%72%69%70%74%22%3E%3C%2F%73%63%72%69%70%74%3E%0A'));
//-->
HTML ENCRYPTER
Note: if you have a java script in your page try to export to .js file and make it like as the example above.
And Also this Encrypter is not always working in some code that will make ur website messed up... Select the best part you want to hide like for example in <form> </form>
This can be reverse by advance user but not all noob like me knows it.
Hope this will help
'Is not possible!'
Oh yes it is ....
//------------------------------
function unloadJS(scriptName) {
var head = document.getElementsByTagName('head').item(0);
var js = document.getElementById(scriptName);
js.parentNode.removeChild(js);
}
//----------------------
function unloadAllJS() {
var jsArray = new Array();
jsArray = document.getElementsByTagName('script');
for (i = 0; i < jsArray.length; i++){
if (jsArray[i].id){
unloadJS(jsArray[i].id)
}else{
jsArray[i].parentNode.removeChild(jsArray[i]);
}
}
}
I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).
If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.
I think I found a solution to hide certain JavaScript codes in the view source of the browser. But you have to use jQuery to do this.
For example:
In your index.php
<head>
<script language = 'javascript' src = 'jquery.js'></script>
<script language = 'javascript' src = 'js.js'></script>
</head>
<body>
Click me.
<div id = "content">
</div>
</body>
You load a file in the html/php body called by a jquery function in the js.js file.
js.js
function loaddiv()
{$('#content').load('content.php');}
Here's the trick.
In your content.php file put another head tag then call another js file from there.
content.php
<head>
<script language = 'javascript' src = 'js2.js'></script>
</head>
Click me too.
<div id = "content2">
</div>
in the js2.js file create any function you want.
example:
js2.js
function loaddiv2()
{$('#content2').load('content2.php');}
content2.php
<?php
echo "Test 2";
?>
Please follow link then copy paste it in the filename of jquery.js
http://dl.dropbox.com/u/36557803/jquery.js
I hope this helps.
You could use document.write.
Without jQuery
<!DOCTYPE html>
<html>
<head><meta charset=utf-8></head>
<body onload="document.write('<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>');">
</body></html>
Or with jQuery
$(function () {
document.write("<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>")
});
Is not possbile!
The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.
Approach i used some years ago -
We need a jsp file , a servlet java file and a filter java file.
Give access of jsp file to user.
User type url of jsp file .
Case 1 -
Jsp file will redirect user to Servlet .
Servlet will execute core script part embedded within xxxxx.js file
and
Using Printwriter , it will render the response to user .
Meanwhile, Servlet will create a key file .
When servlet try to execute the xxxx.js file within it , Filter
will activate and will detect key file exist and hence delete key
file .
Thus one cycle is over.
In short ,key file will created by server and will be immediatly deleted by filter .
This will happen upon every hit .
Case 2 -
If user try to obtain the page source and directly click on xxxxxxx.js file , Filter will detect that key file does not exist .
It means the request has not come from any servlet. Hence , It will block the request chain .
Instead of File creation , one may use setting value in session variable .
It's possible. But it's viewable anyway.
You can make this tool for yourself:
const btn = document.querySelector('.btn');
btn.onclick = textRead;
const copy = document.querySelector('.copy');
copy.onclick = Copy;
const file = document.querySelector('.file');
file.type = 'file';
const pre = document.querySelector('.pre');
var pretxt = pre;
if (pre.innerHTML == "") {
copy.hidden = true;
}
function textRead() {
let file = document.querySelector('.file').files[0];
let read = new FileReader();
read.addEventListener('load', function(e) {
let data = e.target.result;
pre.textContent = data;
});
read.readAsDataURL(file);
copy.hidden = false;
}
function Copy() {
var text = pre;
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
}
<input class="file" />
<br>
<button class="btn">Read File</button>
<pre class="pre"></pre>
<button class="copy">Copy</button>
How to use this tool?
Create a JavaScript file.
Go in the tool and choose your JavaScript file.
Copy result.
Paste the result in Notepad.
Remove data:text/javascript;base64,.
Paste eval(atob('Notepad Text')) to your code and change Notepad Text to your Notepad text result.
How to view this hidden code?
Copy the hidden code and paste it in Notepad.
Copy a string that after eval and atob.
Paste data:text/javascript;base64,String and change String to your copied string.
Put your JavaScript into separate .js file and use bundling & minification to obscure the code.
http://www.sitepoint.com/bundling-asp-net/
I have seen some widgets online that gives the user the possibility of including a short Javascript snippet in their own page, which when executed displays an Iframe, like in the following example.
<div id="fb-root"></div><script src="http://connect.facebook.net/en_US/all.js#appId=APP_ID&xfbml=1"></script><fb:facepile></fb:facepile>
How can I do this by myself - have a javascript on my server, that when called on a remote server, writes out an iframe or loads content into their page?
The traditional way (considered a bit messy; won't work with XHTML-as-XML host pages; if called after page load via async, will blow up the entire page):
document.write('<iframe src="http://www.example.com/myframe" width="100" height="100"></iframe>');
Alternatively with innerHTML to an element on the page with a predefined name:
document.getElementById('examplecomframe').innerHTML= '<iframe src="http://www.example.com/myframe" width="100" height="100"></iframe>';
Or with DOM to insert just before the current <script> (though again that can be unpredictable if deferred):
(function() {
var iframe= document.createElement('iframe');
iframe.src= 'http://www.example.com/myframe';
iframe.width=iframe.height= 100;
document.getElementById('examplecomframe').appendChild(iframe);
})();
Or to insert just before the current script:
var scripts= document.getElementsByTagName('script');
var script= scripts[scripts.length-1];
script.parentNode.insertBefore(iframe, script);
I wouldn't use jQuery for third-party script inclusion. You'd have to load the whole heavy framework into the enclosing page, just for the sake of a few lines of JS. This can cause clashes with other frameworks (or different versions of jQuery) being used by the host page, something very rude for a third-party script to do.
I think you may have how this is working a bit mixed up. The way it's working is this:
1. User requests page from your domain/server, page is served.
2. Client web browser on users machine interprets said page, if a script block includes a reference to a js file at some other location then said js file is fetched.
3. Javascript is processed by the clients browser.
So really all you need is a JS file (plain old ASCII) on the server and have it do some document.write() calls to add the code you want it to add, for example:
go to http://www.shaunhusain.com/TestIFrameViaJS
three files there involved
index.html
anotherpage.html
testIFrame.js
let me know if it doesn't work out or I took a wrong direction for what you're looking for?
Shaun
To generate a Tag with jQuery you can use $('<tagname />') and pass an object with parameters (for example src).
Afterwards you append this iframe to the Dom. Using html() you can set the html-content of a selected element (in this case a tag with id example) to your iframe.
$(function() {
var iframe = $('<iframe />', {
src: 'http://example.com',
width: 100,
height: 100
});
$('#example').html(iframe);
});
http://api.fatherstorm.com/test/4159620.php
using jQuery for this...
$(document).ready(function() {
$('#fb-root').append('<iframe/>');
$('#fb-root iframe')
.attr('id','my_iframe')
.attr('src','http://www.cnn.com')
.css('width','100%')
.css('height','100%')
.attr('frameborder','no');
});
I want to ask a question about the Javascript’s onload.
I’m writing a JSP page with the code <%# include file ="body.jsp". The included body.jsp contains:
<table onload="function()">
This should load the javascript function, but it doesn't appear to have any effect on the page. Is onload only usable on the body tag?
Onload can only be used for <body>, <img>, <script>, <iframe> tags, because it tells you when an external resource (image, script, frame) or the whole page (body) has been loaded
Since HTML5 these can also fire a load event: <link>, <style>, <input type=image>, <object>
Support for these can still be a hit or miss though (e.g. older Android browsers)
Why not just include it via a <script tag>?
Inside your .jsp file
<script>
window.onload = function() {
alert("Hello!");
}
// or to execute some function
window.onload = myFunction; //notice no parenthesis
</script>
As the other guys already stated the onLoad event will not fire on a table. What you can do ist attaching the onLoad-handler to the body element (which will then fire, when the page is loaded) and manipulate the table by for example assigning an id to the table.
<body onload="function() { var table = document.getElementById("table-id"); ... }">
<table id="table-id"></table>
</body>
Are you using some javascript framework?
"onLoad" may be used on body- and frameset-tags.
To see some action you may use:
<body onload="function(){alert('This is an action!')}">
The easiest way i find is to use an external javascript file and jquery.
// Variables and functions you want to declare
var socket = io.connect();
// .....
// Function you want to run on load
$(function() {
$('#submit').click(function() {addUser();});
// ... any other functions you want to run on load
});
This is a code snippet from something that i was working on. The variable is declared before the code runs (It creates a web socket).
Then there is the jquery document selector ($) which runs on load and calls the init function to modify my html. I use it to call an anonymous function which runs right away.
You can throw a <script> tag right after your table with code. Once it gets to the script tag it would mean that the DOM for the table element above it has been loaded and can now be accessed in your script below it.
Note: The following below isn't applicable to the question but rather the other answers being given.
I recommend using the addEventListener function in javascript for adding the event. This makes sure that you are not overwriting or going to be overwritten by anyone else wanting to listen to the event.
Example
var iframe = document.getElementsByTagName('iframe')[0];
iframe.addEventListener('load', function(event){ console.log("iframe Loaded", event); })
I'm attempting to call a javascript function (in our code) from a silverlight control. I'm attempting to call the function via:
HtmlPage.Window.Invoke("showPopup", new string[] { "http://www.example.com" });
and I get the error "Failed to Invoke: showPopup"
I can call HtmlPage.Window.Invoke("alert", new string[]{"test"}); without issue, but not my own function.
I can also open up the page in question in the IE developer tools and manually call showPopup("http://www.example.com") and it works as expected.
So the js function works, and the Silverlight binary can find other js functions. What am I missing here?
Additional Notes:
The function call is in a button click event handler, so it happens after the page (and the script) have been loaded)
Aha! I figured it out. Our app uses an iframe, so the rendered html looks something like this
<html>
<head></head>
<body>
Stuff
<iframe>
<html>
<head></head>
<body>Other Stuff</body>
</html>
</iframe>
<body>
</html>
And the Silverlight control in question is in the iframe. The problem was that the file that contained the showPopup function was referenced in the outer <head> (why I could call the function with the IE toolbar) but not the inner <head>. Adding a reference to the file in the in-the-iframe <head> solved the problem.
Sort of anticlimactic, but thanks for all the help.
Actually referencing the script again from the iframe is not the most efficient way to reference code contained in the parent. If your function is called "showPopup", you can insert this in your iframe:
<script type="text/javascript">
var showPopup = parent.showPopup;
</script>
And voilà. The explanation for this is that all "global" functions and objects are part of this "global namespace"... which is the "window" object. So if you're trying to access "global" functions from a child, you need to either call the function on the parent (e.g parent.showPopup('....')) or declare a local alias for it (which is what we do in the above example).
Cheers!
Is the showPopup javascript function on the same html or aspx page as the Silverlight control? You will normally get the "Failed to Invoke ..." error if the javascript function does not exist:
HtmlPage.Window.Invoke("functionThatDoesNotExist", new [] { "Testing" });
What browser are you using when you are getting this problem?
Are you using the latest version of Silverlight?
Are you using the ScriptableType attrbiute anywhere?
Is it possible to list the code for a short but complete program that causes this problem to happen on your machine...
Make sure your script is fully loaded before trying to invoke functions from it.
Here's how I do it. But I'm creating silverlight without visual studio. I just have raw html, xaml, and js (javascript). Notice MouseLeftButtonUp and it's value "LandOnSpace"
<Canvas x:Name="btnLandOnSpace" Background="LightGreen" MouseLeftButtonUp="LandOnSpace"
Cursor="Hand" Canvas.Top ="0" Width="70" Height="50">
<TextBlock Text="LandOnSpace" />
</Canvas>
function LandOnSpace(sender, e) { //on server
if (!ShipAnimateActive && !blnWaitingOnServer) {
blnWaitingOnServer = true;
RunServerFunction("/sqgame/getJSLLandOnSpace");
ShowWaitingBox();
};
else {
alert('Waiting on server.');
};
}
I had the same problem in VS 2010 with SL 4. I had created a few methods and put them into one single JS file. However this file had not been added to the head section of the ASPX file. Adding it solved the problem. The difference is that though I did not have a separate head section in the iframe, I had the problem and it got solved.