Strip hash from url - javascript

How do get the hash url to output something cleaner? Its doing this:
domain.com/#/page/1
When I want it to do this:
domain.com/page/1
$(document).ready(function(){
var newHash = '';
$('#wrapper a').live('click', function(e){
if (this.hostname && this.hostname == location.hostname) {
e.preventDefault();
var link = $(this).attr('href');
window.location.hash = link;
}
});
$(window).bind('hashchange', function() {
newHash = window.location.hash.substr(1);
$('#content').fadeOut(100).load(newHash + ' #contentInner', function(){
$('#content').fadeIn(100);
});
});
});

Try :
var url = "domain.com/#/page/1";
var noHash = url.split("/#").join("");

That's what a hash is supposed to look like - the # portion is the hash. If you don't want a hash in your url, then do:
window.location = link;
instead.

if (location.href.indexOf("#") > -1) {
location.assign(location.href.replace(/\/?#\//, "/"));
}

Related

Whatsapp share button for web version

I have this script but its only share from mobile version.
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = ".whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
} else {
alert("Please use an Mobile Device to Share this Status");
}
});
});
Can anyone modify this?
This line
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
checks for mobile and if true, the share logic is executed. In the else branch (meaning it's not a mobile) you get an error message. If you want the same to happen in both versions, just omit the if:
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
//if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = ".whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
//} else {
//alert("Please use an Mobile Device to Share this Status");
}
});
});
According the WhatsApp docs: https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat/?lang=en
To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext
Example: https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing`
The result should be something like:
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
// this 3 rows will be used for both - desktop and mobile
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var whatsapp_url = ".whatsapp://send?text=" + message;
} else {
var whatsapp_url = "https://wa.me/?text=" + message;
}
// again for both
window.location.href = whatsapp_url;
});
});

Onclick after effects animation (bodymovin.js) ID nothing happens

I have a after effects bodymovin.js SVG animation with ID's on certain paths (image attached). I've put some css styles on these (cursor:pointer), which work fine but using jquery onClick for a redirect doesn't seem to be working. Any ideas why?
The animation itself is in an overlay which starts after a button is pressed.
The redirect code:
<script>
$(function() {
document.getElementById("replay").onclick = function () {
location.href = "www.yoursite.com";
};
});
</script>
The animation code:
<script>
$( ".animation" ).click(function() {
var anim;
var elem = document.getElementById('bodymovin_overlay')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_overlay.json'
};
anim = bodymovin.loadAnimation(animData);
});
</script>
Also the image is attached:
Remove # from document.getElementById("#replay").
Use document.getElementById("replay") (Native JS) or via jQuery $('#replay')
I believe the error occurs because you forgot to add a semi-colon.
var elem = document.getElementById('bodymovin_overlay')
to
var elem = document.getElementById('bodymovin_overlay');
Issue solved - the overlay was covering the animations z-index, had to give it a higher z-index than the overlay.
Final code that worked, hope it helps someone:
var lookingForLinks = true;
setTimeout(addLinksToSvgAnim, 1000);
function addLinksToSvgAnim() {
if (lookingForLinks) {
let medicalG = document.getElementById("medical");
let foodG = document.getElementById("food");
let collabG = document.getElementById("collab");
let volunteersG = document.getElementById("volunteers");
let projectsG = document.getElementById("projects");
let replayG = document.getElementById("replay");
if (medicalG && foodG && volunteersG && projectsG) {
lookingForLinks = false;
medicalG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/medical-aid";
});
foodG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/humanitarian-aid";
});
collabG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/our-story/partners";
});
volunteersG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/get-involved";
});
projectsG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/bringhope-projects";
});
replayG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/bringhope-projects";
});
}
setTimeout(addLinksToSvgAnim, 1000);
}
}

Chrome Extension - Rerun extension script after redirecting current tab

I am trying to develop a chrome extension which parses data from the current tab and post it to a url which does processing on the data. In certain cases the page may need to be redirected so that certain get parameters are present. My popup.js can successfully do the redirect, but I need to click on the extension a second time to get it to run properly. Note: it runs properly if the page has the correct parameters. How can I adjust this so that the code reruns after the redirect and posts the new source to the specified url.
Here is my popup.js:
var url = "";
chrome.runtime.onMessage.addListener(function(request, sender) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
url = tabs[0].url;
if (url.search("[?&]view=list") == -1)
{
url = setGetParameter(url,'view','list');
chrome.tabs.update(tabs[0].id,{url:url});
process(request);
}
});
process(request);
});
function process(request) {
if (request.action == "getSource") {
message.innerText = request.source;
var data = new FormData();
data.append('source',request.source);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
message.innerText = xhttp.responseText;
}
}
xhttp.open("POST","http://127.0.0.1:5000/api/scraper",true);
xhttp.send(data);
}
}
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
function setGetParameter(url, paramName, paramValue)
{
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
return url + hash;
}
window.onload = onWindowLoad;
Take a look at webRequest.onBeforeRedirect, this event fired when a redirect is about to be executed. You can listen to this event and do your logic again.
Don't forget to declare webRequest permission along with host permissions for any hosts whose network requests you want to access in you manifest.json.

How to check URL format

I want to check whether the url format is #Url.Content("~/Dashboard/Index?studentId="). If it is, we have to set #Url.Content("~/Dashboard/Index"), if not window.location.href. How to do it?
var currentUrl = (#Url.Content("~/Dashboard/Index?studentId=")) ? (#Url.Content("~/Dashboard/Index")) : window.location.href;
if (currentUrl.indexOf('#') > -1) {
currentUrl = currentUrl.replace('#', '');
}
else {
currentUrl += '#';
}
window.location.href = currentUrl;

Equivalent function in Javascript from jQuery

$.ajax({
url: 'http://' + window.location.host + '/',
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
I couldn't find a way to do the same in javascript, I can make ajax call like this
request = new XMLHttpRequest();
request.open('GET', 'http://' + window.location.host + '/', true);
request.onload = function(files) {
if (request.status >= 200 && request.status < 400){
// Success!
resp = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
but how do I get the list of the files in the directory?
CSJS and/or SSJS both answers are okay.
My main goal is not to use jQuery to accomplish what I want.
If you want to loop through the a:contains(.jpg) like in your jQuery example, your best bet is probably to use a DocumentFragment and then call .querySelectorAll on it :
var div = document.createElement('div');
div.innerHTML = request.responseText;
// if you want to search using text
var links = div.querySelectorAll('a')
for (i = 0; i < links.length; i++) {
var link = links[i];
if (!~link.innerHTML.indexOf('.jpg'))
continue;
// found one !
}
// if you want to search using an attribute
var links = div.querySelectorAll("a[href*='.jpg']");
You can dump the response text into a newly created <div> and use the standard methods to access the anchors; the following should even work for IE7:
// $(resp)
var doc = document.createElement('div');
doc.innerHTML = resp;
// .find('a')
var anchors = doc.getElementsByTagName('a'), // get all anchors
container = document.getElementById('some_id');
// .filter(":contains(.jpg)")
for (var i = 0; i < anchors.length; ++i) {
var contents = anchors[i].textContent || anchors[i].innerText || '';
if (contents.indexOf('.jpg') != -1) {
// var images = $(this).attr("href");
// $('<p></p>').html(images).appendTo
var para = document.createElement('p'),
text = document.createTextNode(anchors[i].href);
para.appendChild(text);
container.appendChild(para);
}
}

Categories