This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Running a function by typing in URL
On my website I have several functions that when a hyperlink is clicked on example.php page, the main content changes accordingly. Now I want to direct people from a single URL to that example.php page with the function already called. Example - www.example.com/example.php?AC ( which will call a function named AC and the content changes before the page loads)
I had already asked the same question, but forgot to tag javascript and tagged php.
Thanks in advanced.
You can use JavaScript to get the querystring, and call the functions accordingly.
How to get querystring in JavaScript: JavaScript query string
What I would do is read the query string by using something like this to figure out if the key is there
function doesKeyExist(key) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
return qs != null;
}
Then
if(doesKeyExist(AC)) {
// run my code
}
You could do:
var query = document.location.search;
var func = window[query];
if (func && typeof(func) == "function")
func();
<script language="javascript">
var k = document.location.toString().split('?');
if(k.length > 1)
{
if(k[1] == "AC")
AC();
}
</script>
You can add a window.onload handler, check the query string of the page and act accordingly.
For example:
<html>
<body>
<script>
function handleOnload()
{
if(location.search == "?AC")
alert("the query string is " + location.search);
}
window.onload=handleOnload;
</script>
</body>
</html>
You run a JS funciton like this.
<script type="text/javascript">
function test()
{
alert('test');
}
</script>
Now if you type javascript:test() in the url it will execute test function.
Related
I am trying to create a URL shortener using jsonbase.com and vanilla javascript.
button tag in HTML was not able to recognize the method "shortUrl" from my js file. So, I directly added the code of add event listener in the js file.
index.html
<body>
<div id="app">
<input type="url" id="urlinput">
<input id="mybutton" type="button" value="Short the URL"/>
</input>
</div>
<script src="src/index.js"></script>
</body>
Now, I am getting an error - Javascript type error - The "listener" argument must be of type Function. Received type object - when I am trying to use jsonbase.com for storing the data.
script.js
function shortUrl() {
var longurl = getURL();
genHash();
var uniqueHash = window.location.hash.substr(1);
sendRequest(longurl, uniqueHash);
if (window.location.hash !== "") {
var short = getRequest(uniqueHash);
if (short !== "") {
window.location.herf = "short";
}
}
}
use of jsonbase.com
var jsonbase = require("jsonbase.com");
var token = "mytoken";
var store = jsonbase(token);
var endpoint = `jsonbase.com/${token}`;
//sending request
function sendRequest(longURL, uniqueHash) {
store.write(`${endpoint}/${uniqueHash}`, longURL);
}
//getting request
function getRequest(uniqueHash) {
return store.read(`${endpoint}/${uniqueHash}`).then((response) => {
return response.data;
});
}
generating hash for shorter
function genHash() {
if (window.location.hash === "") {
window.location.hash = getRandomStr();
}
}
Error screenshot -
I have created a reproducible sample code sandbox for my private application - https://codesandbox.io/s/url-shortner-t3ov2
Please let me know if any more info is required.
The issue is not your code, the issue is the package not parsing the JSON correctly, try using a different package
I know this does not answer your question, but it should solve it
This question already has answers here:
How to get the title of HTML page with JavaScript?
(4 answers)
Closed 3 years ago.
I´m trying to get the current html title of a page in Javascript. I'm using the getElementsByTagName("title") function but it just returns me undefined.
I´m looking to output the title and substring 23 chars.
I hope someone can help me.
code:
function printName(){
document.onLoad()
var strng = document.getElementsByTagName("title")[0];
var resfin = strng.substring(0, strng.length - 23);
document.write(resfin)
}
UPDATE: I tried this:
<button onclick="printName(-23)">Try it</button>
<br>
<script>
function printName(sub) {
var str = document.title.substring(0, document.title.length + sub);
document.write(str)
}
printName(-23);
</script>
and now its printing out nothing.
I'd simply use document.title
function pageTitle(sub){
return document.title.substring(0, document.title.length + sub)
}
console.log( pageTitle(-23) )
https://developer.mozilla.org/en-US/docs/Web/API/Document/title
You can use
document.title
I would advise you to review this:
https://developer.mozilla.org/en-US/docs/Web/API/Document/title
I have a list in one file html called "filed1":
<ul>
<li>Nombre:<a class="boton" onclick=move() title="Caja">Caja</a><br>
<FONT SIZE=2>Fecha: 21/12/1994</font></font></li>
</ul>
Now I want to change a string in other html "filed2":
<a id="logo-header2">
<h1>
<span class="site-name" id="element">Details</span><br>
</h1>
</a>
Using Java Script:
function move() {
mywindow = window.open("file2.html");
mywindow.document.getElementById("element").innerHTML="Changed");
}
But there is an error which says that mywindow.document.getElementById("element") is NULL, why? The id element exists in the other window. Is there another way to change the string?
The problem is that you are trying to retrieve the DOM element before the window is loaded.
Try following
mywindow.onload = function() {
mywindow.document.getElementById("element").innerHTML="Changed";
}
Like #nikhil mentioned, mywindow is undefined when you're calling it, and you'll need to place your code into something triggered by the onload event.
Another approach you can try is perhaps passing the string as a variable in the url, like so:
function move(){
window.open("file2.html?str=Changed");
}
And then in file2.html, try something that runs on page load:
window.onload = function(){
var str = $_GET('str');
document.getElementById("element").innerHTML = str;
};
function $_GET(q){
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1){
var query = document.location
.toString()
.replace(/^.*?\?/, '')//Get the query string
.replace(/#.*$/, '')//and remove any existing hash string
.split('&');
for(var i=0, l=query.length; i<l; i++){
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
return $_GET[q];
}
The $_GET function I included is just for getting query string parameters, and function much like $_GET[] in php.
I need to do some ugly stuff. But I cannot do it another way. what I need is
<a href='some/url/?with¶ms' onclick="(if confirm('Do you wanna submit?')
{some code to submit form in href property})">
but I don't know how to make inline script work... and I hesitate about the way of submitting it with window.location or document.location. Any ideas?
Try this:
on html:
Submit
<script type="text/javascript" src="myValidation.js" />
myValidation.js
I used json and javascript closures on this answer.
; //starts with this to close other js not yet closed
var MyValidation = {
actionSubmit : function() {
//your code go here
//example of calling another function
MyValidation.anotherFunction();
//example of accessing a global variable (for your validation)
MyValidation.variable;
//example of declaring local variable
var word = "hello";
//example of calling another function with parameters
MyValidation.anotherFunctionWithParameters(word, MyValidation.variable);
//the returning
return MyValidation.someValidation(word);
}
//Yes, this is a comma.
//I'm putting in the beginning so we see this and didn't forget :)
,anotherFunction : function() {
//some code
//maybe a return
}
,variable : {}
,anotherFunctionWithParameters : function(param1, param2) {
//more code, maybe a return
}
,someValidation : function(parameter) {
//some validation
return true|false;
}
};
Take a look on this:
How do JavaScript closures work?
json
Have you heard about AJAX? Google it if you don't.
The onClick parameter accepts a function name with or without parameters, not "inline scripts".
<script type=text/javascript>
function doStuff(){
if(confirm("Submit?"){
//do your stuff with AJAX to some/url/?with¶ms
}
}
</script>
<a href='javascript:doStuff'>link</a>
I have some JS from an external JS file that I want to insert inside of a JS function in the HTML file. I can not touch the JS script in the HTML file, so I am wondering if this method can be done.
Here is the JS I want to insert inside of the JS function in the HTML file.
// FIRST JS TO INSERT
if (OS == "mobile"){
killVideoPlayer();
}
// SECOND JS TO INSERT
if (OS == "mobile"){
loadHtmlFiveVideo();
if (!document.all){
flvPlayerLoaded = false;
}
}else {
loadVideoPlayer();
}
Then I want to insert it into here.
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
// INSERT FIRST JS HERE
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("frame_photo").style.display = "none";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "none";
// INSTER SECOND JS HERE
loadVideoPlayer();
}
if (bsiCompleteArray[arrayIndex].mediaType == "photo") {
killVideoPlayer();
document.getElementById("bsi-video-wrap").style.display = "none";
document.getElementById('pngBsi').style.display = "block";
document.getElementById("relativeFrame").style.display = "block";
document.getElementById("frame_photo").style.display = "block";
document.getElementById("buy-me-photo-button-bsi").style.display = "block";
if (!document.all){
flvPlayerLoaded = false;
}
}
}
</script>
Thank you!
In JavaScript, you can overwrite variables with new values at any time, including functions.
By the looks of it, you could replace the mediaTypeCheck function with one of your own that does what you need and then calls the original function.
E.g.
(function(){
// keep track of the original mediaTypeCheck
var old_function = mediaTypeCheck;
// overwrite mediaTypeCheck with your wrapper function
mediaTypeCheck = function() {
if ( conditions ) {
// do whatever you need to, then ...
}
return old_function();
};
})();
The above can be loaded from any script, so long as it happens after the mediaTypeCheck function is defined.
The easiest way for me in the past has been using server-side includes. Depending on your back end, you can set up a PHP or ASP page or whatever to respond with a mime type that mimics ".js".
I'm not a PHP guy, but you'd do something like this: (if my syntax is incorrect, please someone else fix it)
<?php
//adding this header will make your browser think that this is a real .js page
header( 'Content-Type: application/javascript' );
?>
//your normal javascript here
<script>
function mediaTypeCheck() {
if (bsiCompleteArray[arrayIndex].mediaType == "video") {
//here is where you would 'include' your first javascript page
<?php
require_once(dirname(__FILE__) . "/file.php");
?>
//now continue on with your normal javascript code
document.getElementById("bsi-video-wrap").style.display = "block";
document.getElementById('pngBsi').style.display = "block";
.......
You cannot insert JS inside JS. What you can do is insert another tag into the DOM and specify the SRC for the external JS file.
You can directly insert js file using $.getScript(url);
if you have script as text then you can create script tag.
var script = docuent.createElement('script');
script.innerText = text;
document.getElementsByTagName('head')[0].appendChild(script);
The issue in your case is that you cannot touch the script in the html, so I'll say that it cannot be done on the client side.
If you could at least touch the script tag (not the script itself), then you could add a custom type to manipulate it before it executes, for example:
<script type="WaitForInsert">
Your question looks some strange, but seems to be possible. Try my quick/dirty working code and implement your own situation:
$(document.body).ready(function loadBody(){
var testStr = test.toString();
var indexAcc = testStr.indexOf("{");
var part1 = testStr.substr(0, indexAcc + 1);
var part2 = testStr.substr(indexAcc + 1, testStr.length - indexAcc - 2);
var split = part2.split(";");
split.pop();
split.splice(0,0, "alert('a')");
split.splice(split.length -1, 0, "alert('d')");
var newStr = part1 + split.join(";") + ";" + "}";
$.globalEval(newStr);
test();
}
function test(){
alert('b');
alert('c');
alert('e');
}