How can I show content on a page based on query string? - javascript

I'm working with a team that is using a vendor's web based application. When people log out, they are redirected to the login page, where we would like to add a message. We don't have access to change the code (it's cloud hosted) but we can pass a query string parameter in the URL.
We can do something like:
http://our.site.com?logout=true
From there, I'd like to display a message in an h2 or something.
We can customize the HTML, CSS and JS of the page, but we don't have access to the source of the application (otherwise I would do this in PHP).
I presume I can use JS to change some CSS, but in all my trials I cannot get the CSS to actually change.

Check this answer: Get url parameter jquery Or How to Get Query String Values In js
var logout = getUrlParameter('logout');
if(typeof logout !== "undefined")
{
// show some div with display: none
// or put some content to the existing div
}

From your question above, I am just understanding that you need a piece of code to show some message on your login page on the basis of the query string received.Following is the piece of code you can add in the footer of your login page html(as you have the access to html).
<script type="text/javascript">
function getParamValue(querystring) {
var qstring = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < qstring.length; i++) {
var urlparam = qstring[i].split('=');
if (urlparam[0] == querystring) {
return urlparam[1];
}
}
}
if(getParamValue('logout')=='true'){
var messageDiv = document.createElement("div"); // Creating a div to display your message
var message = document.createTextNode("You have successfully logged out."); // Preparing the message to show
messageDiv.appendChild(message); // Appended the message in newly created div
var addIn = document.getElementById("login"); //just presuming there is a div having id="login" in which you want to prepend the message
addIn.insertBefore(messageDiv, addIn.childNodes[0]); //just appended the message on top of login div
//setting style in your message div
messageDiv.style.backgroundColor ="#FF0000";
messageDiv.style.width ="100%";
}
</script>
Then change the link of login page like this:
http://our.site.com/login.php?logout=true
Note :Read the code comments carefully to edit the code as per your html structure.

Try !important to change CSS? Just a temporary solution until you can edit the actual code.

Related

My code executed only in console but not working in .js file

I have tried the following code to replace text character to the img tag inside div message.
However the code is working fine while i do in console. But when I try the same in my sticker.js is not working. Can anyone tell me the reason?
The idea to make sticker box for chat app codded with Javascript and jQuery.
User 1 will send :sticker1: to public room and replaced with img src inside the #div
Now I'm trying document to call the script when div is showing but still not working.
$(document).ready(function() is not working
And $(function() is not working either.
My chat app using template folder /template/*.php and web-cache folder to load the design. I am searching every where to find some solution but no luck.
I need help please
$("#chat-sticker-container").ready(function stickers() {
var emoCodes = [
':sticker1:',
];
var $this = $("body");
emoCodes.forEach(function(code) {
var image = '<img src="https://sevendays.co.in/wp-content/uploads/2019/02/' + code.replace(/:/g, "") + '.jpg">';
$this.find('p.chat-sticker').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="js/sticker.js"></script>
<dive id="chat-sticker-container">
<p id="chat-sticker" class="chat-sticker">:sticker1:</p>
</dive>
Make sure your JS is executing AFTER the html is in the DOM, this includes putting your script at the end of your body tag.
Since the script is called before the html is defined its essentially working with nothing, putting the after the html should fix the issues.
By looking at your JSFiddle example I think you need to use the MutationObserver API. This way you can check if an element, or the children of an element have been changed, added or removed.
I'm not able to figure out what the container is where the chat divs are added to the page, so I can only instruct you. But based on your fiddle I'm selecting the chat-main-scroll-chatroom div.
// List of emoCodes
var emoCodes = [
':sticker1:',
];
// Select chat container. Change if necessary.
var chatContainer = document.getElementById('chat-main-scroll-chatroom');
// Create a new observer.
var observer = new MutationObserver(function(entries) {
// Check for emocodes whenever something has changed.
emoCodes.forEach(function(code) {
var image = '<img src="https://sevendays.co.in/wp-content/uploads/2019/02/' + code.replace(/:/g, "") + '.jpg">';
$('p.chat-sticker').html(function(index, html) {
return html.replace(new RegExp(code, "g"), image);
});
});
});
// Check if children are changed
var options = { childList: true }
// Observer the chat container and check if itself or children are changing.
observer.observe(chatContainer, options);
So I really hope that this will help you out. In the best case scenario you would be able to filter the text that has been sent before the message is sent. If the API of your chat app provides such controls, then please use them.
Best of luck!

Modifying chrome extension for new Twitter UI

I have a chrome extension for Twitter where I add a button to all those tweets which have images in them. The code in the content script is something like this:
$(".tweet, .js-tweet").each(function() {
var username = $(this).attr('data-screen-name');
var tweetid = $(this).attr('data-tweet-id');
if (username != null) {
var mediaLinkContainer = $(this).find(".card2")
addButtonToMediaLinkTweets(tweetid, mediaLinkContainer)
// addOverlayToMediaLinks()
var outerContainer = $(this).find(".AdaptiveMediaOuterContainer")
var mediaContainer = $(this).find(".AdaptiveMedia-photoContainer")
if (mediaContainer.length) {
console.log("Photo found in link")
addButtonToPosts(tweetid, outerContainer)
// addOverlayToPosts(outerContainer)
}
}
});
This worked perfectly with the older UI of Twitter, but this doesn't work after the new UI was rolled out. All the class names have changed and the view hierarchy is different as well. I'm trying to navigate through all of that to make my extension work again.
The following class name appears a lot of times - css-1dbjc4n I tried the following to iterate over all the tweets:
$('.css-1dbjc4n.r-1ila09b.r-qklmqi.r-1adg3ll').each(function() {
console.log($(this).html())
})
.css-1dbjc4n r-1ila09b r-qklmqi r-1adg3ll are the classes assigned to the div that is at the second to top most level of a tweet (the topmost div does not have a class or id). However, console.log does not print anything in this case. I need to iterate over the tweets to be able to add my UI element.
Edit:
It seems that jQuery has issues with the new Twitter UI. When I wrote the following in vanilla JavaScript:
var tweetDivs = document.getElementsByClassName("css-1dbjc4n r-1ila09b r-qklmqi r-1adg3ll")
console.log(tweetDivs)
//get images inside the tweets and add button on top of these images
$(tweetDivs).each(function(tweet) {
console.log(tweet)
})
I get a HTML collection in tweetDivs. However, I'm unable to iterate over its elements as its length is 0. The elements show up in console though, but that's probably because the DOM hasn't loaded when this gets called. That's weird because I'm calling the above code from document.ready. I tried replacing document.ready with document.addEventListener("DOMContentLoaded", function(){}) and changed run_at in manifest.json file to document_start but it did not make a difference.

How to clear form behind modal window with javascript?

Just like the question says, I'm trying to clear a form from a modal window while the modal stays up. I've tried:
if (myDocument.title == "Modal Window") {
parent.document.getElementById("textbox")
}
(I need it to do more than 1 tb, but used that just to try to get there. No luck.
It is contained within an iFrame, so I tried:
if (myDocument.title == "Modal Window") {
var ifr = document.getElementById("iFrame")
var form = ifr.document.getElementById("form")
ClearForm(form)
}
The ClearForm(form) function I stole from another Stack Overflow answer:
function ClearForm(form) {
$(':input', form).each(function () {
var type = this.type;
var id = this.id;
if (type == 'text' && id != 'text2')
this.value = "";
});
}
That 'text2' is one specific tb that we need to remain populated.
Any idea what I'm missing? I've been plagued with this bug for weeks.
I expect your issue is that the form is within an iFrame - most browsers won't allow you to modify elements within an iFrame, from the parent page, if they aren't from the same origin (or if the server is set up to deny it, or if you're looking at the page locally... see here for more details)
To double-check, try moving the form markup into the same page as the modal is in and run your function ClearFormfrom there. I expect that you'll then find it works.
Your only way around this would be to include the ClearForm function within the iFrame'd page, and then trigger it from the parent.

Adding and removing elements on a web page dynamically using javascript

So I'm using Twitter Bootstrap to create a web page, and I'd like to use their "Alerts" class to dynamically create and dismiss alerts at the bottom of my page. Basically my web page is used to monitor a wireless data acquisition system, so I'd like to be able to dynamically display messages related to that system, i.e. "Warning, Sensor 1 is not responding", and then be able to dismiss it dynamically when the event has passed, or have the user dismiss it.
I'm more of an embedded systems guy, and haven't done much web development, so I'm really not sure where to start. My first inclination would be to do something like this:
<div id="Alert1"></div>
<div id="Alert2"></div>
...
And create enough divs at the bottom of my page to display a reasonable number of messages, then dynamically change them in code with something like:
var Alert1 = document.getElementById("Alert1");
Alert1.className = "alert alert-warning";
$('#Alert1').html("Error: Unable to write to logfile");
I can't imagine that this is a very good way to do it, though, and I'd have to have some way to manage what divs were in use, etc. What is a better way to dynamically create and remove these elements?
Using jQuery you can use append to dynamically add an element to the page.
<div class="alerts"></div>
In JavaScript:
$(".alerts").append("<div id='alert1'>Warning</div>");
Similarly you can remove the element using the remove() function.
You don't need to create a <div> for any and all error messages you have. Just create one <div> and dynamically fill in the appropriate text (or HTML) of the currently active message.
Sample code:
// define this function globally
(function (exports) {
var messages = {};
function addMessage(type, msg) {
if (typeof messages[type] === "undefined") {
messages[type] = [];
}
messages[type].push(msg);
render();
}
function render() {
var html = "";
for (type in messages) {
if (messages.hasOwnProperty(type)) {
for (var i=0, len=messages[type].length; i<len; i++) {
html += type + ": " + messages[type][i];
}
}
}
$("#Alert").html(html);
}
exports.addMessage = addMessage;
})(window);
// somewhere in your code
addMessage("Error", "Unable to write to logfile");
It would be even better to declare "Error" as a constant/variable somewhere:
var ERR_ERROR = "Error";
var ERR_WARNING = "Warning";
You can define a template for your alerts, holding the message and the type of the message.
Then according to the type of the message you would append the message into the page.
Consider the following function
function addAlert(type, message) {
_.templateSettings.variable = "element";
var tpl = _.template($("#alertTemplate").html());
var tplData = {
message: message,
type: type
};
$("#mainContainer").append(tpl(tplData));//the div or container where you want your messages to appear
}
And the template would be
<script type="text/html" id="alertTemplate">
<div class = "alert alert-<%= element.type %>" > <%= element.message %> </div>
</script>
and of course the container of your alerts
<div id="mainContainer">
</div>
Then in your alert handler you would call addAlert with the appropriate parameters.
and to remove all the alerts
$("#mainContainer").find('.alert').remove();
You can find working example at http://jsfiddle.net/hatemalimam/EpM7W/6/

Add parameter to URL with Javascript

I have a web page with a jQuery lightbox that opens automatically on page load. In the lightbox I have implemented the Facebook Like button (this is a 2 click solution for Facebook Like button in email). Now, when a Facebook user visits my web page by clicking on the "Liked" URL on Facebook I want to turn off the lightbox. I don't want to have to create two different pages (one with lightbox turned on and another turned off) and I think I can avoid this by adding a parameter to the URL with Javascript then turn the lightbox on/off based on that parameter. Is this a safe way to do this? How would I do this?
You can get URL params with this JS function that I found here:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
Then *add use ?lightbox=1 e.g www.example.com?lightbox=1 and read it with the above function:
if(getUrlVars()["lightbox"]=="1"){
//...
}
*to add parameters you can either:
Change the a link href attribute element.href = "http://www.newURL.com?param=1"; and wait for the user to click them
Redirect to the new location window.location.href = "http://www.newURL.com?param=1";
I believe this is the rough code you're after:
<script type="text/javascript">
document.location="http://example.com/index.php?noLightBox=1";
</script>
Then on index.php, you'd want something such as:
<?php
function isset_or(&$check, $alternate = NULL)
{
return (isset($check)) ? (empty($check) ? $alternate : $check) : $alternate;
}
function getGETPOST($var)
{
return isset_or($_GET[$var],isset_or($_POST[$var],"Empty"));
}
?>
Example:
if(getGETPOST('noLightBox') != 1) {
// Code to display the light box comes here.
}
// Else normal page code
Hope this was helpful!
Source: http://php.net/manual/en/function.isset.php
& W3School's tutorials on PHP

Categories

Resources