Is it possible to call a javascript function from the URL? I am basically trying to leverage JS methods in a page I don't have access to the source.
Something like: http://www.example.com/mypage.aspx?javascript:printHelloWorld()
I know if you put javascript:alert("Hello World"); into the address bar it will work.
I suspect the answer to this is no but, just wondered if there was a way to do it.
There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.
There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Write in address bar
javascript:alert("hi");
Make sure you write in the beginning: javascript:
/test.html#alert('heello')
test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>
you may also place the followinng
<a href='javascript:alert("hello world!");'>Click me</a>
to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show
About the window.location.hash property:
Return the anchor part of a URL.
Example 1:
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
Using Eddy's answer worked very well as I had kind of the same problem.
Just call your url with the parameters : "www.mypage.html#myAnchor"
Then, in mypage.html :
$(document).ready(function(){
var hash = window.location.hash;
if(hash.length > 0){
// your action with the hash
}
});
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
Just use:
(function() {
var a = document.createElement("script");
a.type = "text/javascript";
a.src = "http://www.example.com/helloworld.js?" + Math.random();
document.getElementsByTagName("head")[0].appendChild(a)
})();
This basically creates a new JavaScript line in the head of the HTML to load the JavaScript URL you wish on the page itself. This seems more like what you were asking for. You can also change the a.src to the actual code, but for longer functions and stuff it becomes a problem. The source link can also link to a JavaScript file on your computer if targeted that way.
No; because it would make links extremely dangerous.
you can execute javascript from url via events
Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>
does work if params in url are there.
There is a Chrome extension called Bookmarklet URL (no affiliation). To append a URL with JavaScript, so that the JavaScript command is executed just after loading the webpage, one can use ?bmlet=javascript:
Example: Display an alert box
https://github.com/?bmlet=javascript:alert("Hi");
Example: Enable spell-checking while editing a GitHub README file
[Obviously, a spelling checking extension must be originally available.]
https://github.com/<username>/<repositoryname>/edit/main/README.md?bmlet=javascript:document.getElementById("code-editor").setAttribute("spellcheck","true");
On some pages, it might take some time, as the JavaScript command runs after completely loading the page. Simple commands like alert("Hi"); should run quickly.
I am a student and I have just realized my school blocked JavaScript from the address bar. It works with the "a" tag on a .html file but not on the bar anymore. I am not asking for help, I would just like to share this.
You can do one thing that is you can first open the link www.example.com. Then you can search:
javascript:window.alert("Hello World!")
Related
I'm having problems getting this to work. I first tried setting my script tags as strings and then using jquery replaceWith() to add them to the document after page load:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
But I got string literal errors on that var. I then tried encoding the string like:
var a = '&left;script type="text/javascript">some script here<\/script>';
but sending that to replaceWith() outputs just that string to the browser.
Can someone please let me know how you would go about dynamically adding a <script> tag into the browser after page load, ideally via jQuery?
You can put the script into a separate file, then use $.getScript to load and run it.
Example:
$.getScript("test.js", function(){
alert("Running test.js");
});
Try the following:
<script type="text/javascript">
// Use any event to append the code
$(document).ready(function()
{
var s = document.createElement("script");
s.type = "text/javascript";
s.src = "http://scriptlocation/das.js";
// Use any selector
$("head").append(s);
});
http://api.jquery.com/append
Here's the correct way to do it with modern (2014) JQuery:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.appendTo('head');
})
or if you really want to replace a div you could do:
$(function () {
$('<script>')
.attr('type', 'text/javascript')
.text('some script here')
.replaceAll('#someelement');
});
A simpler way is:
$('head').append('<script type="text/javascript" src="your.js"></script>');
You can also use this form to load css.
This answer is technically similar or equal to what jcoffland answered.
I just added a query to detect if a script is already present or not.
I need this because I work in an intranet website with a couple of modules, of which some are sharing scripts or bring their own, but these scripts do not need to be loaded everytime again. I am using this snippet since more than a year in production environment, it works like a charme. Commenting to myself: Yes I know, it would be more correct to ask if a function exists... :-)
if (!$('head > script[src="js/jquery.searchable.min.js"]').length) {
$('head').append($('<script />').attr('src','js/jquery.searchable.min.js'));
}
Here is a much clearer way — no need for jQuery — which adds a script as the last child of <body>:
document.body.innerHTML +='<script src="mycdn.js"><\/script>'
But if you want to add and load scripts use Rocket Hazmat's method.
Example:
var a = '<script type="text/javascript">some script here</script>';
$('#someelement').replaceWith(a);
It should work. I tried it; same outcome. But when I used this:
var length = 1;
var html = "";
for (var i = 0; i < length; i++) {
html += '<div id="codeSnippet"></div>';
html += '<script type="text/javascript">';
html += 'your script here';
html += '</script>';
}
$('#someElement').replaceWith(a);
This worked for me.
Edit: I forgot the #someelement (btw I might want to use #someElement because of conventions)
The most important thing here is the += so the html is added and not replaced.
Leave a comment if it didn't work. I'd like to help you out!
There is one workaround that sounds more like a hack and I agree it's not the most elegant way of doing it, but works 100%:
Say your AJAX response is something like
<b>some html</b>
<script>alert("and some javscript")
Note that I've skipped the closing tag on purpose. Then in the script that loads the above, do the following:
$.ajax({
url: "path/to/return/the-above-js+html.php",
success: function(newhtml){
newhtml += "<";
newhtml += "/script>";
$("head").append(newhtml);
}
});
Just don't ask me why :-) This is one of those things I've come to as a result of desperate almost random trials and fails.
I have no complete suggestions on how it works, but interestingly enough, it will NOT work if you append the closing tag in one line.
In times like these, I feel like I've successfully divided by zero.
If you are trying to run some dynamically generated JavaScript, you would be slightly better off by using eval. However, JavaScript is such a dynamic language that you really should not have a need for that.
If the script is static, then Rocket's getScript-suggestion is the way to go.
Is it possible to call a javascript function from the URL? I am basically trying to leverage JS methods in a page I don't have access to the source.
Something like: http://www.example.com/mypage.aspx?javascript:printHelloWorld()
I know if you put javascript:alert("Hello World"); into the address bar it will work.
I suspect the answer to this is no but, just wondered if there was a way to do it.
There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.
There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.
You can use Data URIs.
For example:
data:text/html,<script>alert('hi');</script>
For more information visit: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Write in address bar
javascript:alert("hi");
Make sure you write in the beginning: javascript:
/test.html#alert('heello')
test.html
<button onClick="eval(document.location.hash.substring(1))">do it</button>
you may also place the followinng
<a href='javascript:alert("hello world!");'>Click me</a>
to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show
About the window.location.hash property:
Return the anchor part of a URL.
Example 1:
//Assume that the current URL is
var URL = "http://www.example.com/test.htm#part2";
var x = window.location.hash;
//The result of x will be:
x = "#part2"
Exmaple 2:
$(function(){
setTimeout(function(){
var id = document.location.hash;
$(id).click().blur();
}, 200);
})
Example 3:
var hash = "#search" || window.location.hash;
window.location.hash = hash;
switch(hash){
case "#search":
selectPanel("pnlSearch");
break;
case "#advsearch":
case "#admin":
}
Using Eddy's answer worked very well as I had kind of the same problem.
Just call your url with the parameters : "www.mypage.html#myAnchor"
Then, in mypage.html :
$(document).ready(function(){
var hash = window.location.hash;
if(hash.length > 0){
// your action with the hash
}
});
you can use like this situation:
for example, you have a page: http://www.example.com/page.php
then in that page.php, insert this code:
if (!empty($_GET['doaction']) && $_GET['doaction'] == blabla ){
echo '<script>alert("hello");</script>';
}
then, whenever you visit this url: http://www.example.com/page.php?doaction=blabla
then the alert will be automatically called.
Just use:
(function() {
var a = document.createElement("script");
a.type = "text/javascript";
a.src = "http://www.example.com/helloworld.js?" + Math.random();
document.getElementsByTagName("head")[0].appendChild(a)
})();
This basically creates a new JavaScript line in the head of the HTML to load the JavaScript URL you wish on the page itself. This seems more like what you were asking for. You can also change the a.src to the actual code, but for longer functions and stuff it becomes a problem. The source link can also link to a JavaScript file on your computer if targeted that way.
No; because it would make links extremely dangerous.
you can execute javascript from url via events
Ex: www.something.com/home/save?id=12<body onload="alert(1)"></body>
does work if params in url are there.
There is a Chrome extension called Bookmarklet URL (no affiliation). To append a URL with JavaScript, so that the JavaScript command is executed just after loading the webpage, one can use ?bmlet=javascript:
Example: Display an alert box
https://github.com/?bmlet=javascript:alert("Hi");
Example: Enable spell-checking while editing a GitHub README file
[Obviously, a spelling checking extension must be originally available.]
https://github.com/<username>/<repositoryname>/edit/main/README.md?bmlet=javascript:document.getElementById("code-editor").setAttribute("spellcheck","true");
On some pages, it might take some time, as the JavaScript command runs after completely loading the page. Simple commands like alert("Hi"); should run quickly.
I am a student and I have just realized my school blocked JavaScript from the address bar. It works with the "a" tag on a .html file but not on the bar anymore. I am not asking for help, I would just like to share this.
You can do one thing that is you can first open the link www.example.com. Then you can search:
javascript:window.alert("Hello World!")
So I have an interesting dilemma that I am trying to resolve. I am using FancyBox and when using it, it requires that loading an iframe has an href tag and a url set.
In the present form, a user selects a square, and then enters in an amount, and then clicks a button - which fires (opens) fancybox.
What I would like it to do is to modify the href url each step of the way.
For example, starting url is say:
http://www.domain.com/do.php
On the click of the square, it then becomes
http://www.domain.com/do.php?s=3
Then on entering an amount the url appends to be:
http://www.domain.com/do.php?s=3&amount=20
I've found some references to changing a url, but they all seem to be changing the url for browser history. So I am wondering if anyone could lead me in the right direction so that I can accomplish this?
Any insight is greatly appreciated. Thanks!
You can append to the URL by using the below method:
HTML
<input type="button" id="btnGo" onclick="getUrl()"/>
JavaScript
function getUrl() {
var currentUrl = window.location.href;
setUrl(currentUrl);
}
function setUrl(url) {
var result = url + "?anotherargument";
window.location.href = result;
}
If I understand your question correctly, you have to reload the url of an Iframe.
There is simple javascript-only solution for that. See example here: http://jsfiddle.net/ddan/2tf3vyLb/2/
Uploading src attribute of Iframe:
function appendToUrl(str){
document.getElementById('f1').src += str;
}
in your case the parameter first is ?s=3, second time &amount=20
You want to change the href of the iframe?
Have you tried simply setting it like so
$('#square').click(function(){
$('iframe').attr('href', $('iframe').attr('href') + '?s=3')
})
$('#amount_button').click(function(){
$('iframe').attr('href', $('iframe').attr('href') + '&amount=' + $('#amount').val())
})
I'm trying to make a new pin it button just like Pinterest has, I've see the content at that bookmark:
javascript:void(
(function(){
var e=document.createElement('script');
e.setAttribute('type','text/javascript');
e.setAttribute('charset','UTF-8');
e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);
document.body.appendChild(e)
})()
);
I'm new to javascript, so I am not sure how to start to do a new one. I have even no idea where should I start my coding. Is the backend for this Pin it button limited? Can anyone introduce how does this Pin it button works? Thank you so much.
Basically what that code does is injects a <script> tag into the page. The actual "pin it" code is located in the pinmarklet.js file.
To make your own feature like this, you can just reuse the code and replace the source with your own JavaScript file.
Side-note: the void(...) part is redundant because the function doesn't return anything anyway.
The code you posted simply injects a JavaScript file into the page's DOM which will cause it to get interpreted by the JavaScript engine. What you should be more interested in is the code in this file which implements the "Pin It" functionality:
http://assets.pinterest.com/js/pinmarklet.js
But since that is minified and somewhat obfuscated and probably proprietary, I would suggest what you want first is an easy to follow tutorial on how to create a Bookmarklet:
http://betterexplained.com/articles/how-to-make-a-bookmarklet-for-your-web-application/
Then, you need to think about how you will code your own web application to respond to asynchronous requests to "Pin" or save something. The following two simple but useful JavaScript variables could come in handy if you're just going for a simple "link-submission" type of functionality:
document.location.href -- to get the page's URL
document.title -- to get the contents of the page's TITLE tags
To compress your code into a single-line as is required by bookmarklets, you could use this tool:
http://subsimple.com/bookmarklets/jsbuilder.htm
If you want to add it to a button here is how:
html:
<button id="pintrest">Pin It</button>
And you script:
var btn = document.getElementById("pintrest");
btn.onclick = function () {
var e = document.createElement('script');
e.setAttribute('type', 'text/javascript');
e.setAttribute('charset', 'UTF-8');
e.setAttribute('src', 'http://assets.pinterest.com/js/pinmarklet.js?r=' + Math.random() * 99999999);
document.body.appendChild(e);
};
Now when you click on the button it should run the pintrest code
I'd like to invoke a mailto link from JavaScript - that is I'd like a method that allows me to open the email client on the users PC, exactly as if they had clicked on a normal mailto link.
How can I do this?
You can use window.location.href here, like this:
window.location.href = "mailto:address#dmail.com";
You can avoid the blank page issue discussed above by instead using .click() with a link on the page:
document.getElementById('mymailto').click();
...
the working answer for me, tested in chrome, IE and firefox together with outlook was this
window.location.href = 'mailto:address#dmail.com?subject=Hello there&body=This is the body';
%0d%0a is the new line symbol of the email body in a mailto link
%20 is the space symbol that should be used, but it worked for me as well with normal space
Better to use
window.open('mailto:address#mail.com?subject=sub&body=this is body')
If we use window.location.href chrome browser is having error in network tab with Provisional headers are shown
Upgrade-Insecure-Requests: 1
Actually, there is a possibillity to avoid the empty page.
I found out, you can simply insert an iframe with the mailto link into the dom.
This works on current Firefox/Chrome and IE (also IE will display a short confirm dialog).
Using jQuery, I got this:
var initMailtoButton = function()
{
var iframe = $('<iframe id="mailtoFrame" src="mailto:name#domain.com" width="1" height="1" border="0" frameborder="0"></iframe>');
var button = $('#mailtoMessageSend');
if (button.length > 0) {
button.click(function(){
// create the iframe
$('body').append(iframe);
//remove the iframe, we don't need it any more
window.setTimeout(function(){
iframe.remove();
}, 500);
});
}
}
This is an old question, but I combined several Stack Overflows to come up with this function:
//this.MailTo is an array of Email addresses
//this.MailSubject is a free text (unsafe) Subject text input
//this.MailBody is a free text (unsafe) Body input (textarea)
//SpawnMail will URL encode /n, ", and ', append an anchor element with the mailto, and click it to spawn the mail in the users default mail program
SpawnMail: function(){
$("#MyMailTo").remove();
var MailList="";
for(i in this.MailTo)
MailList+=this.MailTo[i]+";";
var NewSubject=this.MailSubject.replace(/\n/g, "%0d%0a");
NewSubject=NewSubject.replace(/"/g, "%22");
NewSubject=NewSubject.replace(/'/g, "%27");
var NewBody=this.MailBody.replace(/\n/g, "%0d%0a");
NewBody=NewBody.replace(/"/g, "%22");
NewBody=NewBody.replace(/'/g, "%27");
$("#mainNavBar").after("<a id='MyMailTo' style='display:none;' href='mailto:"+MailList+"?subject="+NewSubject+"&body="+NewBody+"'> </a>");
document.getElementById('MyMailTo').click();
}
The cool part about this (and how I plan to use it) is I can put this in a loop and split out individual messages to everyone in the array or keep everyone together (which is what this function currently does).
Anyway thanks for the tip #Toskan
FOLLOW-UP - Please note the new HTML5 standard does not allow looping mailto (or other pop-up related js) without a "required user gesture". Cool article here: https://github.com/WICG/interventions/issues/12
So you can't use this to mass generate individual e-mails, but it does work well with sending to many in it's current design.