Linking Directly To An Open Modal Window Through a URL? - javascript

I don't know much at all about coding so hopefully i worded the question correctly.
What I am trying to do is link a person to a specific modal window on another website. In this example, I will use the Menards weekly ad to show what I would like to do.
I would like to link somebody directly to the weekly flyer page with the modal window already open for a specific product such as the $74.99 5 Shelf Unit, which when selected opens this window (http://i.imgur.com/lntNUpK.png). This is the window that I would like to directly link to somebody.
Is there a way to modify the URL to make this possible? About all I know how to do is how to link to a specific page of the URL which would look like this /main/flyer.html?page=5
One other thing to mention is if you go to the website that provides the ads, Flipp, it does allow you to directly link to the window https://flipp.com/item/175356457-muscle-rack-5shelf-steel-unit
Thanks for any help!

Yes it is possible with some javascript, it will look for #myModal on the url if it finds it, it will load the modal:
just put this at the end of your page:
$(document).ready(function() {
if(window.location.href.indexOf('#myModal') != -1) {
$('#myModal').modal('show');
}
});
Now just use the following url:
http://www.mywebsite.com/page.html#myModal
*your modal must have an id:
<div class="modal" id="myModal">

How about that?
function openModalOnHash() {
if(window.location.hash) {
var hash = window.location.hash.substring(1);
$('#'+hash).modal('show');
}
}
$(document).ready(function() {
openModalOnHash()
});

I believe this should work. Only opens modal (if modal exist) with specified ID in URL
$(document).ready(() => {
const href = window.location.href
const modalID = href.split('/').reverse()[0]
if(modalID){
$(modalID).modal('show')
}
})

Yes, you can catch get param on url , https://www.exampleurl.com/?param=ModalIdShow
// Start Page
$(function(){
var param = GetURLParameter('param');
if(param == 'ModalIdShow'){
$("#ModalIdShow").modal("show");
}
});
//Catch param
function GetURLParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}

Related

Javascript change location href and click on a certain button

I would like to redirect the user onclick to a certain page "user/logged_in1" if the user is not already on that page and after the redirect a certain button must be clicked. This button opens a modal.
Doesn't work with this function:
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
location.href="user/logged_in1";
document.getElementsByClassName("zimmerbtn")[0].click();
}
}
It seems it searched already for the button before the redirect happens and therefore the list is empty. How to fix this?
EDIT
This is a little bit more complex. The modal should only open if the user uses the redirect. If I use onload on the body tag, the modal will always open if the page is loaded, I don't need that. I need that modal only to be opened if the redirect happens.
The whole thing is a Python flask application:
{% if current_user.zahlung_iban == None and have_this_user_a_room != None %}
<li><a class="btn mybtn" onclick="redirect_to_logged_in_and_open_modal()" data-toggle="modal" data-target="#premium-special-modal"> Zimmer anbieten </a></li>
{% else %}
<li><a class="btn mybtn" href="{{ url_for('zimmer_einstellen') }}"> Zimmer anbieten </a></li>
{% endif %}
As you see there is a certain trigger for the button to become the redirect button.
EDIT
Okay working with a cookie sounds like a possible solution. But I cant figure out how to delete the cookie after the button was clicked, none of the proposed code works, eventhough it looks simple:
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
location.href="user/logged_in1";
document.cookie = "redirected_coz_of_click";
}
}
$( document ).ready(function() {
if ($(".logged-in-container")[0]) {
var delete_cookie = function(name) {
document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};
if (document.cookie.indexOf('redirected_coz_of_click') > -1 ) {
document.getElementsByClassName("zimmerbtn")[0].click();
delete_cookie('redirected_coz_of_click');
console.log(document.cookie);
} else {
console.log("cookie removed");
}
}
});
1: Append a parameter to the redirect url
user/logged_in1?click=btn_id
2: On landing on that page you can then check if the parameters is there. Found this method
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
Found the method here: https://stackoverflow.com/a/21903119/3514785
So you could use it like this:
var btnToClickId = getUrlParameter("click");
3: With jquery (or javascript if you want) fire the click event on that btn:
$("#"+btnToClickId).click();
NB: You want to do the check after the page has loaded:
$(window).on("load",function() {
var btnToClickId = getUrlParameter("click")
if(btnToClickId) {
$("#"+btnToClickId).click();
}
});
So in summary
a: Edit your page and remove this line document.getElementsByClassName("zimmerbtn")[0].click(); because it is pointless
b: In the target page in the js copy and past the `getUrlParameter' method.
c: Then inside a on window load event listener do the url check as specified in 3.
ALTERNATIVE TO URL PARAMETER
You could instead use localStorage or some cookie to store the target id right before redirecting. Make sure you remember to clear it in the target page after grabbing it so that it is not always triggered even when you have not redirected from the page that triggers this whole process.
You can not access elements that have not even loaded yet.
By using location.href = '' you are simply directing a user to a page, any javascript after will fail because the page hasn't been loaded yet.
You tell us that you want to redirect a user to a page onclick. This sounds like the essential of an anchor tag:
Click Me
For step 2, just place the javascript on the page you are redirecting to. Bind to the load event of the page and then execute your javascript:
window.onload = function() {
document.getElementsByClassName("zimmerbtn")[0].click();
};
You can use cookie.
Set cookie when user click on the redirect button and when page is loaded, check if the cookie is set and open the modal. When you done with opening the modal clear the cookie. In that way you can easily achieve this.
Instead of triggering click. Call the onclick function in body onload method of user/logged_in1.
<body onload="openModal()">
You are trying to access a content on your initial page, but you have already redirected the user from that page, so this cannot be achieved by the current method.
I believe what you are trying to do is to open up a modal, after redirecting, do the following.
On your redirected page add the following, use jquery to achieve this
$( document ).ready(
// add the functionality to launch modal here
);
I created an onclick() function for this button:
onclick="redirect_to_logged_in_and_open_modal()"
In the function I check if I am not already on the logged_in site. If not I redirect but I add an additional parameter to the URL ?redirected.
In the next step if the logged_in is loaded and the parameter is in the URL the modal will also open, thats it.
Thanks #Zuks for the Idea adding a param to URL.
function redirect_to_logged_in_and_open_modal() {
if(window.location.href.indexOf("logged_in") > -1) {
return
} else {
window.location.assign("https://www.example.com/user/logged_in1?redirected");
}
}
$( document ).ready(function() {
if ($(".logged-in-container")[0]) {
if(window.location.href.indexOf("redirected") > -1) {
document.getElementsByClassName("zimmerbtn")[0].click();
}
}
});

Javascript/html keep url params

say I provide someone with a link to my page that looks like the following
www.linkone.com?something=ten
When they visit the page, the param will be visible within the url for that page. If on that page I then have a link like so
Link Two
When they click on it, Link Two's url will look like
www.linkone.com/linktwo.html
Is there any way to add the param from the first link onto any other links within the page? So when they visit Link Two, I want to url to end up being
www.linkone.com/linktwo.html?something=ten
I know it is probably possible via javascript, but the homepage has a lot of links on it to other pages within the site, and I need to param on all links. What is the best way to achieve this?
Thanks
$('a:not([href=#])').on('click', function (e) {
e.preventDefault();
location.href = this.href + "your param";
});
My suggestion is:
$('a:not([href=#])').click(function(e) {
e.preventDefault();
// Getting query-string parameters from current page URL.
var query = location.search.substr(1);
// Getting URL from current link;
var url = new URL($(this).attr('href'));
// Updating query-string parameters of current link.
url.search += (url.search.indexOf('?') == 0 ? '&' : '?') + query;
// Getting the link target.
var target = $(this).attr('target');
// Navigating to new URL.
if (target) {
window.open(url.toString(), target);
} else {
location.assign(url.toString());
}
});
One way to achieve a similar function is to use cookies or session. When a user visits your site with additional param, set a cookie on the parent page with that param so that it would be available for other calls/links. You could do that in session as well. session would retain the value till the session times out and cookie expires based on the expiry date set for it.
Link to Cookie Reference
You can update anchors href attributes at Document Ready. Below code solution for current HTML querystrings carries over the selected anchors href attributes.
var selectedAnchors = $("a");
selectedAnchors.each( function () {
var itemHref = $(this).attr("href");
if ( itemHref.indexOf("?") > -1 )
itemHref += "&";
else
itemHref += "?";
itemHref += location.search.substr(1);
$(this).attr("href", itemHref );
});
Please try this. Just replace word "something" with your own parameter.
Thanks
$("a").click(function(e){
e.preventDefault();
var a = $(this).attr('href');
var something = getUrlParameter('something');
var newURL = a+"?something="+something;
window.location.href = newURL;
});
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
HTML:
Google
This is possible (with php):
<a href="http://www.linkone.com/linktwo.html?something=
<?php echo $_GET["something"]; ?>"> Link Two </a>

Detect when user close window or presses back button (it's more complicated)

I would like to get a script that lets the user to navigate on your site and use the back button without any questions until it's the same domain. Otherwise ask the visitor if he really wants to leave the site.
I was able to write the part that take cares of the navigation. See here:
window.onload = function() {
var links = document.links;
for (var i = 0; i < links.length; i++)
links[i].addEventListener('click', function() {
window.onbeforeunload = null;
});
};
window.onbeforeunload = function() {
window.setTimeout(function() {
location.assign('http://www.google.com');
}, 0);
return 'WAIT BEFORE YOU GO!\nClick "STAY ON THIS PAGE" and let me show you something!';
};
However I can't find any reference regarding the back button. If there was any event for this, I would approach the problem with something like this:
<on_back_button_event> = function () {
if (document.referrer.split('/')[2] == location.hostname)
window.onbeforeunload = null;
}
As I mentioned, I got stuck here. Any ideas are welcomed.

Make a link from Electron open in browser

Is there any (simple/built-in way) to open a new browser (I mean default OS browser) window for a link from Electron instead of visiting that link inside your Electron app ?
You can simply use :
require("shell").openExternal("http://www.google.com")
EDIT: #Arjun Kava's answer is much better these days.
This answer is quite old and assumes you have jQuery.
const shell = require('electron').shell;
// assuming $ is jQuery
$(document).on('click', 'a[href^="http"]', function(event) {
event.preventDefault();
shell.openExternal(this.href);
});
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
require('electron').shell.openExternal(url);
});
Requires that you use target="_blank" on your anchor tags.
My code snippet clue accordingly to the depreciations in Electron version ^12.0.0
const win = new BrowserWindow();
win.webContents.setWindowOpenHandler(({ url }) => {
// config.fileProtocol is my custom file protocol
if (url.startsWith(config.fileProtocol)) {
return { action: 'allow' };
}
// open url in a browser and prevent default
shell.openExternal(url);
return { action: 'deny' };
});
To make all Electron links to open externally in the default OS browser you will have to add an onclick property to them and change the href property so it doesn't load anything in the Electron app.
You could use something like this:
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}
But make sure the entire document has loaded before doing this otherwise it is not going to work.
A more robust implementation would look like this:
if (document.readyState != "complete") {
document.addEventListener('DOMContentLoaded', function() {
prepareTags()
}, false);
} else {
prepareTags();
}
function prepareTags(){
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}
return false;
}
Remember that if you load external files you will have to make them go through this process as well after they are fully loaded.
Some handy solutions can be found in this gist.
By listening on the body, the following solutions will work on <a> tags that may not yet exist when the JavaScript runs, but only appear in the DOM at a later time.
This one by luizcarraro requires jQuery:
$('body').on('click', 'a', (event) => {
event.preventDefault();
require("electron").shell.openExternal(event.target.href);
});
You can change the selector to target only certain links, e.g. '#messages-view a' or 'a.open-external'.
Here is an alternative without any library (derived from zrbecker's):
document.body.addEventListener('click', event => {
if (event.target.tagName.toLowerCase() === 'a') {
event.preventDefault();
require("electron").shell.openExternal(event.target.href);
}
});
Consult the gist for more examples.
I use this method with Electron v.13.
We intercept the user's navigation (window.location) and open the URL in the default browser.
See the doc : https://www.electronjs.org/docs/latest/api/web-contents#event-will-navigate
const { shell } = require('electron');
window.webContents.on('will-navigate', function (e, url) {
e.preventDefault();
shell.openExternal(url);
});
On tsx syntax (Electron):
import { shell } from "electron";
shell.openExternal("http://www.google.com")
In the view component use simple a link:
<a href="https://google.com" target="_blank" rel="noreferrer">
<button type="button">
button title
</button>
</a>
And in file public/electron.js add default behavior for all a link navigations:
function createWindow() {
...
// Open urls in the user's browser
win.webContents.setWindowOpenHandler((edata) => {
shell.openExternal(edata.url);
return { action: "deny" };
});
}
To open an external link in an Electron's Project you will need the module Shell (https://www.electronjs.org/docs/api/shell#shell) and the method openExternal.
But if you are looking for an abstract way to implement that logic is by creating a handler for a custom target to your target attribute.
const {shell} = require('electron');
if (document.readyState != "complete") {
document.addEventListener('DOMContentLoaded', function() {
init()
}, false);
} else {
init();
}
function init(){
handleExternalLinks();
//other inits
}
function handleExternalLinks(){
let links = document.getElementsByTagName('a')
let a,i = 0;
while (links[i]){
a = links[i]
//If <a target="_external">, so open using shell.
if(a.getAttribute('target') == '_external'){
a.addEventListener('click',(ev => {
ev.preventDefault();
let url = a.href;
shell.openExternal(url);
a.setAttribute('href', '#');
return false;
}))
}
console.log(a,a.getAttribute('external'))
i++;
}
}
To run an Electron project in your actual browser (Chrome, Mozilla, etc), add this to your script are external script:
aTags = document.getElementsByTagName("a");
for (var i = 0; i < aTags.length; i++) {
aTags[i].setAttribute("onclick","require('shell').openExternal('" + aTags[i].href + "')");
aTags[i].href = "#";
}

Chrome extension: Execute some code if a specific tab is not found

I am developing a chrome extension and after it is installed it iterates through opened tabs and if the required Tab is not found then I open a new tab. Following is my code:
var found = false;
chrome.tabs.getAllInWindow(null, function(tabs){
for (var i = 0; i < tabs.length; i++) {
var tabUrl = tabs[i].url;
if (tabUrl == 'http://www.youtube.com') {
chrome.tabs.update(tabs[i].id,{url:someUrl,selected:true});
found = true;
}
}
});
if (!found) {
window.open('https://www.youtube.com/watch?v=somevideid');
}
The problem is that whether the youtube is found or not the NOT FOUND if condition always return true and the default video URL is opened where as it should only open if youtube tab is not found. I think the Last if condition is not at the right place, any idea?
You should use chrome.tabs.query() instead of chrome.tabs.getAllInWindow(). The .query method, if called with an empty queryInfo object, will find ALL the tabs.
So, your code should be like this:
chrome.tabs.query({}, function(tabs) {
var found = false;
for (var i=0; i < tabs.length; i++) {
if (/https?:\/\/www\.youtube\.com/.test(tabs[i].url)) {
found = true;
chrome.tabs.update(tabs[i].id, {url: 'https://www.youtube.com/watch?v=somevideid', active: true});
break; // you found it, stop searching and update the tab
}
}
if (!found) chrome.tabs.create({url: 'https://www.youtube.com/watch?v=somevideid', active: true});
// you didn't find it, create a new tab with the new url and select it
});
Also, I used the regexp /https?:\/\/www\.youtube\.com/ to test the url of the tab, because the url may begin with "http" or "https", or may have some query string attached, like "?hl=en" or similars, so using tab[i].url == "http://www.youtube.com/" will not provide you absolute certainty of finding the tab.

Categories