HTML and Native Javascript Change Iframe content based on search query - javascript

I've made a website that utilizes Bootstrap's tab navigation. For my blog, I have an iframe set into one of these tabs. I am currently trying to make it so that if I were to give someone a link with the query ?blogPost=a_post it would automatically redirect the SRC of the Iframe to /blog/a_post.html. I started by setting up the script to get the queries based on this article: https://www.sitepoint.com/get-url-parameters-with-javascript/. Then, I adapted the code to look like this:
function onload() {
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
if (urlParams.has('blogPost')) {
let blogPost = urlParams.get('blogPost');
document.getElementById('pills-home-tab').classList.remove('active');
document.getElementById('pills-blog-tab').classList.add('active');
document.getElementById("child-iframe").src = `./blog/${blogPost}.html`;
} else {
return;
}
}
window.onload = onload;
However, when I load the page https://website.com/?blogPost=welcome_to_my_blog none of the classList properties change, and the Iframe stays at /blog.html
I'm not sure where I'm going wrong, but I'm certain what I'm trying to do is possible, and under that assumption know I am at error in my code. No errors come up on my browser's console, either.

You declared a global function called onload, this has overwritten the native window.onload, making it not work. You can change the name of your function, or just add directly like this:
window.onload = () => {
let queryString = window.location.search;
let urlParams = new URLSearchParams(queryString);
if (urlParams.has("blogPost")) {
let blogPost = urlParams.get("blogPost");
document.getElementById("pills-home-tab").classList.remove("active");
document.getElementById("pills-blog-tab").classList.add("active");
document.getElementById("child-iframe").src = `./blog/${blogPost}.html`;
}
};

Related

Adding parameters to url on page load only if no paremeters already exist

I searched for the answer to my question and even tried some solutions, but wasn't able to get anything to really work. I'm newish to javascript, so that might also be why.
I have a specific URL and whenever someone goes to that URL, I want to add parameters to it, but only if no parameters are already present. Parameters get added to the URL for other on click events, but on page load, I need a set of parameters added to the URL.
I tried to use the history API and I think I'm kind of close, but I'm not able to get it to do what I want it to do.
function addDefaultParam(url) {
var currentURL = window.location.href; //get the current url
var baseURL = '/our-partners'; //this is the url that should have params added
var paramString = '?asc=true&sortBy=display_name'; //here are the params
if (currentURL === baseURL) {
window.history.pushState("object or string", "Title", "/" + paramString);
}
return url;
}
I'm using basic js in this because that's what was used in the other functions (I inherited this code). Any help would be greatly appreciated.
You can register the addDefaultParam function to fire when the document first loads in the browser and use the Location interface to check the state of the current path and query string of the URL and if they match your conditions, update the current query string value.
See below for an example:
window.addEventListener("load", addDefaultParam);
function addDefaultParam() {
let currentPath = document.location.pathname;
let currentQueryString = document.location.search;
let targetPath = "/our-partners";
if (currentPath === targetPath && !currentQueryString) {
document.location.search = "?asc=true&sortBy=display_name";
}
}

How could I make it object-oriented

I have a js file which use Storage API. It just save form infos to get them if you have to fill the form again in a new session. It also re-use these infos to put them somewhere else in the page without page refreshing. It's working but I would like to make this in an object-oriented way.
Tried to learn OOP (beginner) and to make a function with the code which isn't in an object working at a window.onload event.
// STORAGE
// Used Elements
let input_textarea = document.querySelector('#firstname_area');
let input_textarea_bis = document.querySelector('#lastname_area');
let chosen_station = document.querySelector('#station')
let output_div = document.querySelector('.personal-greeting');
let output_station = document.querySelector('#custumerstation');
let save_button = document.querySelector('.send');
// Onclick start function
save_button.addEventListener('click', updateOutput);
// Saved Elements
output_div.textContent = localStorage.getItem('content');
input_textarea.value = localStorage.getItem('content');
input_textarea_bis.value = localStorage.getItem('contentbis');
chosen_station.innerHTML = sessionStorage.getItem('content');
// Function actions setting saved elements
function updateOutput() {
localStorage.setItem('content', input_textarea.value);
localStorage.setItem('contentbis', input_textarea_bis.value);
output_div.textContent = input_textarea.value;
output_station.textContent = chosen_station.innerHTML;
}
By creating a FormInformation class you could create attributes for the things you need to repeat elsewhere in your app like input text area fields, etc... This way, you could store an instance of FormInformation and set the attributes with the values of what you got while doing document.querySelector() and reuse it

Bookmarklet to load current page without JavaScript?

I would like to have a bookmarklet to load the current page/tab without its scripts, as if the browser had JavaScript disabled in its settings. Is it possible?
It would work a bit like this Chrome extension: https://chrome.google.com/webstore/detail/toggle-javascript/cidlcjdalomndpeagkjpnefhljffbnlo
But without the "toggle" function, i.e., the bookmarklet wouldn't enable JavaScript.
I like that extension and I would love to have something similar on iOS. It is possible to disable JavaScript in Safari, but it's annoying to open Settings every time I want to load a page without the scripts.
I thought a bookmarklet might allow me to quickly load the current page without it scripts, but I don't know if it's possible. Feel free to suggest other workarounds (maybe using Shortcuts/Workflow?).
One option is to use a userscript: fetch the current page, parse the response text into a document, remove all <script> tags in the document, then open a new window with window.open(), and populate its <head> and <body> with the cleaned document's <head> and <body>:
window.openPageWithoutScripts = async function() {
const resp = await fetch(window.location.href);
const text = await resp.text();
const doc = new DOMParser().parseFromString(text, 'text/html');
doc.querySelectorAll('script').forEach(script => script.remove());
const w = window.open();
w.document.head.innerHTML = doc.head.innerHTML;
w.document.body.innerHTML = doc.body.innerHTML;
};
Then, whenever you want to open the current page without any scripts, open the console and type in openPageWithoutScripts().
This strips out <script> tags, but not inline handlers, which are less predictable and harder to get rid of (though, luckily, they're bad practice and are generally rarer).
To also strip out inline handlers, create an array of all possible events, then iterate over them and querySelectorAll elements with those handlers, and remove the attribute:
window.openPageWithoutScripts = async function() {
const resp = await fetch(window.location.href);
const text = await resp.text();
const doc = new DOMParser().parseFromString(text, 'text/html');
doc.querySelectorAll('script').forEach(script => script.remove());
const eventNames = ['click', 'load', 'error']; // etc
eventNames.forEach((e) => {
const onEventName = 'on' + e;
document.querySelectorAll(`[${onEventName}]`).forEach((elm) => {
elm.removeAttribute(onEventName);
});
});
const w = window.open();
w.document.head.innerHTML = doc.head.innerHTML;
w.document.body.innerHTML = doc.body.innerHTML;
};

get javascript url parameter from script source file in HTML

My HTML block as follows,
<html>
<title>Example</title>
<head>
</head>
<body>
<h2>Profile Photo</h2>
<div id="photo-container">Photo will load here</div>
<script type='text/javascript' src='http://example.com/js/coverphoto.js?name=johndoe'></script>
</body>
</html>
and I have saved this file as test.html. In JavaScript source the name will be dynamic.
I want to collect the name in coverphoto.js. Tried in coverphoto.js as,
window.location.href.slice(window.location.href.indexOf('?') + 1).split('&')
but it is getting the html file name (test.html) only. How can I retrieve the name key from http://example.com/js/coverphoto.js?name=johndoe in coverphoto.js?
To get the URL of the current JavaScript file you can use the fact that it will be the last <script> element currently on the page.
var scripts = document.getElementsByTagName('script');
var script = scripts[scripts.length - 1];
var scriptURL = script.src;
Please note that this code will only work if it executes directly within the JS file, i.e. not inside a document-ready callback or anything else that's called asynchronously. Then you can use any "get querystring parameter" JS (but make sure to replace any location.search references in there) to extract the argument.
I'd suggest you to put the value in a data-name argument though - that way you can simply use e.g. script.getAttribute('data-name') to get the value.
You can use the stack trace technique.
This technique will detect the source of the JS file the script is running from and it doesn't depend on the way you have injected the script. It can be dynamically injected (ajax) or in whatever method you can think of.
Just use the following code in your JS file:
const STACK_TRACE_SPLIT_PATTERN = /(?:Error)?\n(?:\s*at\s+)?/;
const STACK_TRACE_ROW_PATTERN1 = /^.+?\s\((.+?):\d+:\d+\)$/;
const STACK_TRACE_ROW_PATTERN2 = /^(?:.*?#)?(.*?):\d+(?::\d+)?$/;
const getFileParams = () => {
const stack = new Error().stack;
const row = stack.split(STACK_TRACE_SPLIT_PATTERN, 2)[1];
const [, url] = row.match(STACK_TRACE_ROW_PATTERN1) || row.match(STACK_TRACE_ROW_PATTERN2) || [];
if (!url) {
console.warn("Something went wrong. This probably means that the browser you are using is non-modern. You should debug it!");
return;
}
try {
const urlObj = new URL(url);
return urlObj.searchParams;
} catch (e) {
console.warn(`The URL '${url}' is not valid.`);
}
};
const params = getFileParams();
if ( params ) {
console.log(params.get('name'));
}
Note:
The params.searchParams will not work for IE browser, instead you can use params.search. But, for the sake of you nerves don't. Whoever is still using IE in 2020, just let him suffer.

Using jQuery to access a Flash Function

So I’m trying to interact with a flash variables using jQuery. The original author of the flash based program has not got back to me yet and so I thought to ask here. I'm not that strong in AC3 so forgive me.
Within the original action script, I added a new import statement:
import flash.external.*;
There's a function that initializes the program called ini and added this towards the bottom:
//MODS===========
ExternalInterface.addCallback(‘gotoLastPage’,gotoLastPage)
//===============
For all intensive purposes, just know that there is an existing and working function called gotoLastPage. It is declared as private void and works by the default application. All seemed fine there, got no errors when I recompiled the swf file.
Now the swf object is initialized like this
var flashvars = {};
flashvars.pages = “reader_fl/pages.xml”;
flashvars.settings = “reader_fl/settings.xml”;
var params = {};
params.quality = “high”;
params.scale = “noscale”;
params.wmode = “transparent”; var attributes = {};
attributes.align = “middle”;
attributes.allowFullscreen = “true”;
swffit.showScrollV();
swfobject.embedSWF("reader_fl/PageFlip_v6.swf", "Reader_Window_player", "100%", "100%",
"10.0.0", false, flashvars, params, attributes);
As a note, I'm using swfobject. The reader comes up fine and is wrapping around a div called Reader_Window_player.
Now when I go to jQuery, I tried:
$("#Floating_CtrlStart").click(function(){
var Reader = $('#Reader_Window_player')[0];
Reader.gotoLastPage();
})
However, I still can’t seem to access the gotoLastPage. Console says that gotoLastPage is not defined.
Any help here?
Are you opening the html page from the file system and not served from a web server? If so, that would explain why it's not working.
Calls to ExternalInterface fail if the content (html and swf) is in the local-with-networking or local-with-filesystem sandbox (source: http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7c9b.html).
I love JQuery but I usually do that the old fashion way:
var getSwf = function (swfName) {
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[swfName] : document[swfName];
}
getSwf("Reader_Window_player").gotoLastPage();
Also make sure you have the following in your JS:
attributes.id = "Reader_Window_player";
attributes.name = "Reader_Window_player";
and as #Cherniv stated in the comments:
params.allowScriptAccess="always"

Categories

Resources