I am working on checking if string exists on page. And I have some difficulties. I have url that generated by system var url = here it generated it in string format and its in "string" format. So lets say it has for of "url/my" and "url/yours" I make it to be url by #text I need to check if it contains exact word on page in generated url
<script type='text/javascript'>
window.onload = function () {
if (document.body.innerHTML.toString().indexOf('something') > -1) {
alert("It contains 'something'");
}
};
</script>
This is working on the page that was opened, but not on the page of the generated URL. I need to make it work in IF-ELSE statement. Something like
if(url contain word "something")
{
do that
}
So I need somehow pass generated url with href to script and then to if-else statement
You can check url pathname and then make control in your function
let pathname = window.location.pathname
if(pathname.includes('home'))
{
do that
}
Related
I would like to modify a little helper snippet in Google Tag Manager which purpose is to write a certain part of the url with GTM's build-in-var {{Page URL}} as a string into a custom dimension.
At the moment this is done with
function() {
var url = {{Page URL}};
if (url == "https://mywebsite.com/") {
url = "home";
}
else {
url = url.split("/");
url = url[3].split("?");
url = url[0];
}
return url;
}
The goal is now to treat some url's with certain strings different from the other url's. All special url's have in common that they've got a unique combination of string+number which could easily be grabbed by a regex from the url. For example with PID\d+.
I'm relatively new to javascript and don't know how to integrate this additional condition. Should it be done by an „else if“ block for the regex? I've also tried to integrate another if (url == /PID\d+/) {url = "foobar";}. Any ideas how to achieve this?
Lets say I'm on a webpage abc.com/xyz/ and I need the source code of abc.com/xyz?param=true to access a variable, that is not existing without that parameter, as this page relies heavily on JavaScript.
I'm building a Bookmarklet that shows this specific variable and my current workaround is to simply redirect the user with location.href = page + "?param=true", where page is the current site and then instruct them to click again on this Bookmarklet (not user-friendly). If this parameter exists, I can access the variable.
To optimize this I want to load this second webpage in the background with vanilla JS or jQuery (as it's already used by abc.com) but using for e.g. $.get() will show only the webpage with JavaScript disabled.
tl;dr: How can I load another webpage with JS/jQuery and JavaScript enabled/executed?
Edit:
Some pseudo-code
javascript:(function() {
var page = window.location.href;
if(abc.com/.../ AND param=true) {
var variable = document.getElementById("my_var");
// do something with variable
} else if(only abc.com/.../) {
alert("Redirecting...");
location.href = page + "?param=true";
}
})();
Here is an example that checks for the presence of "param=true" in the request string and either appends the param (if not present) or allows for other actions if present:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function checkParam() {
let page = window.location.href;
if (page.indexOf('?param=true') < 0 && page.indexOf('¶m=true') < 0) {
if (page.indexOf('?') > 0) {
window.location.href = page + '¶m=true';
} else {
window.location.href = page + '?param=true';
}
} else {
// dummy code to visualize result. Replace with something more useful
let node = document.getElementById('output');
node.removeChild(node.firstChild);
node.appendChild(document.createTextNode('param= true is set'))
}
}
</script>
</head>
<body onload="checkParam()">
<h1>Test</h1>
<p id="output">"param = true" is missing from the URL</p>
</body>
</html>
The code tries to avoid matching other params like 'someparam=true' and honors the presence of other parameters, if present by either appending with '?' or '&'
In my website I have some part when you 'click' on it, It will show a (pop-up) div & grays the rest of the website, However I want to make a link/hashlink for that state.. something like this ( http://www.mywebsite.com/show-pop-up ), So whenever my visitors type the link above in their browser and go, They will come to my website with (the pop-up visible).
I saw this in Trello.com & Behance.com (When you click in a project it will show as pop-up with a new link in the browser).
Note: I need this in 'pure' JavaScript.
There are several ways you can achieve this. One of the following options may work for you.
Option 1: using hashes. Consider the following url: www.mywebsite.com/index.html#popup. You can retrieve the #popup value on startup of your website and act accordingly. See the code sample below.
document.addEventListener("DOMContentLoaded", function(event) {
// Website has loaded.
var hash = location.hash
// Check if the hash exists and is popup.
if (hash && hash === 'popup') {
// Show your popup
}
});
Another option would be to use query strings. Consider the following url: www.mywebsite.com?popup=true. First you have to retrieve the query strings, using for example the following function. Afterwards check if the popup querystring has been used.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var popup = getParameterByName('popup');
// Check if we have the popup parameter.
if (popup) {
// Show popup
}
Suggest using
http://www.mywebsite.com#show-pop-up
instead of
http://www.mywebsite.com/show-pop-up
then using
if(location.hash === '#show-pop-up') {
// show your popup
}
on page loaded.
I am building a jQuery based web app and I want to use URL parameters to navigate around it.
I would like to display content based on the URL parameter, with the 'load()' function getting the main body of the web page from an external URL and replacing an element with it.
How would I create an if statement that use the following conditions...
If there are no parameters in the url, then use $("#toBeReplaced").load("home.txt");
If the parameter page is equal to about, then use $("#toBeReplaced").load("about.txt");
If the parameter page is equal to contact, then use $("#toBeReplaced").load("contact.txt");
...to determine what page of the app to display.
You can simply load the url using page variable if it is undefined then load home otherwise load whatever is in page variable.
var page = location.search.substring(1).split('=')[1];
if (page == undefined)
$("#toBeReplaced").load("home.txt");
else
$("#toBeReplaced").load(page + ".txt");
You can use different libraries or jQuery plugins to get url parameters in js. For this example I will use js-url. Include the url.min.js file into your page. Then just use this to get the parameter page by url("?page") and create a simple if.
$(function() {
var page = url("?page");
if( page === "about" ) {
$("#toBeReplaced").load("about.txt");
}
else if( page === "contact" ) {
$("#toBeReplaced").load("contact.txt");
}
else {
$("#toBeReplaced").load("home.txt");
}
});
function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.