I'd like to get the security zone (Internet zone / local intranet) for a number of URL's which are in the same domain. I thought the best solution would be to get this through iFrame.
#Teemu. Code works now. Thank you very much. But one problem so far: It displays the wrong text. Although the page is in trusted zone (local intranet) he displays "untrusted" (Internet zone). Any idea why?
<html>
<head>
<script type="text/javascript">
function getZone() {
var text = new Array();
document.getElementsByClass('iframeNames');
var test;
for (var i = 0; i < document.frames.length; i++) {
try {
test = document.frame[i].contentWindow.document;
text[i] = "Trusted (Local Intranet)";
} catch (e) {
text[i] = "Untrusted (Internet Zone)";
}
} //end-for
var showText = getElementsByClass("zone");
for (var i = 0; i < showText.length; i++) {
setText(showText[i], text[i]);
};
} //end getZone()
function setText(showText, text) {
showText.innerHTML = text;
} //end setText
if (document.getElementsByClassName) {
getElementsByClass = function (classList, node) {
return (node || document).getElementsByClassName(classList);
};
}
</script>
</head>
<style type="text/css">
tr:nth-child(2n) {
background-color: #ddd;
}
.format {
background-color: #ffff;}
#formatierung {
margin-left: 10px;
margin-top: 30px;
font-family: Arial;
font-size: 13px;
}
</style>
<body>
<iframe src = "http://example.com" class = "iframeNames" width = "0"
height ="0"></iframe>
<iframe src = "http://example.com/index/" class = "iframeNames" width = "0"
height = "0"></iframe>
<script type = "text/javascript">
window.onload = function() {
getZone();
};
</script>
<div id = "formatierung">
<table width = "100%">
<tr class = "format"><td><h2>System</h2></td><td><h2>Check Security-Zone</h2></td></tr>
<tr><td>example1</td><td class = "zone"></td></tr>
<tr><td>example2</td><td class = "zone"></td></tr>
</table>
</div>
</body>
</html>
You can try this:
var test;
for (var i = 0; i < document.frames.length; i++) {
try {
test = document.frames[i].document;
text[i] = "Trusted (Local Intranet)";
} catch (e) {
text[i] = "Untrusted (Internet Zone)";
}
}
With this code you won't need isTrustedIE() at all.
Like I said in my previous comment, frames[] is a collection of the "window" objects in the document. This code just checks, if it can get a reference to the document in the iframe. It's not possible, when iframe's content is loaded from cross-origin source.
Related
I am working on a memory game and I asked a previous question earlier which was answered. I've had this problem and I haven't been able to find a solution with effort. So it's a memory game and when the cards are clicked, they are pushed into an array which can hold two elements at max (you can only click two cards) and then the two elements' frontSrc is checked if they are the same. I set that using an expando property. If so, have them visible and then clear the array so I can do more comparisons. However, it doesn't seem to be working as intended. I'll attach a video below. I've tried using timeout to set the length again, but that didn't work. It works for the first cards, but the other ones after that, it doesn't work.
Here is my code.
<!DOCTYPE html>
<!--
Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
Click nbfs://nbhost/SystemFileSystem/Templates/Other/html.html to edit this template
-->
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
.card{
width: 35%;
}
#cards{
display: grid;
grid-template-columns:25% 25% 25% 25%;
row-gap: 25px;
}
</style>
</head>
<body onload="init()">
<section id="cards">
</section>
<script>
var arrCards = [];
var arrShowedCards = [];
//appendElements();
function init(){
createCards();
shuffleCards();
appendElements();
}
function createCards(){
var arrCardNames = ["Mouse","Penguin","Pop","Mouse","Penguin","Pop"];
for(var i = 0; i<6; i++){
var card = document.createElement("IMG");
card.src = "Images/red_back.png";
card.className = "card";
card.frontSrc = "Images/" + arrCardNames[i] + ".png";
card.id = "card" + i;
card.addEventListener("click", showCard);
document.getElementById("cards").appendChild(card);
arrCards.push(card);
}
}
function shuffleCards(){
for (let i = arrCards.length-1; i > 0; i--)
{
const j = Math.floor(Math.random() * (i + 1));
const temp = arrCards[i];
arrCards[i] = arrCards[j];
arrCards[j] = temp;
}
return arrCards;
}
function appendElements(){
for(var i = 0; i<arrCards.length; i++){
document.getElementById("cards").appendChild(arrCards[i]);
}
}
function showCard(){
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if(arrShowedCards.length === 2){
if(arrShowedCards[0].frontSrc === arrShowedCards[1].frontSrc){
console.log("Match!");
arrShowedCards = [];
}
else{
console.log("No match!");
setTimeout(function(){
arrShowedCards[0].src = sourceString;
arrShowedCards[1].src = sourceString;
}, 1000);
}
}
}
</script>
</body>
</html>
I am not sure how come it doesn't work for it for the other cards.
Here is the video.
https://drive.google.com/file/d/1aRPfLALHvTKjawGaiRgD1d0hWQT3BPDQ/view
If anyone finds a better way to approach this, let me know.
Thanks!
I think when not match, you need to reset arrShowedCards otherwise its length will be greater than 2 forever.
function showCard() {
var sourceString = "Images/red_back.png";
this.src = this.frontSrc;
arrShowedCards.push(this);
if (arrShowedCards.length === 2) {
var a = arrShowedCards[0], b = arrShowedCards[1];
arrShowedCards.length = 0;
if (a.frontSrc === b.frontSrc) {
console.log("Match!");
} else {
console.log("No match!");
setTimeout(function () {
a.src = sourceString;
b.src = sourceString;
}, 1000);
}
}
}
I build a small application to switch between random images in an iframe, I would like that after 10 or 20 images the user will get an image or source I want him to get and not a random one, and then return to the loop.
I have a problem with the count and if function, will appreciate any help. Thanks
<body>
<iframe id="img_main" src="https://www.example.com/img_4.jpg" width="600" height="800" frameborder="1" scrolling="no"></iframe>
<br>
<button id="H" type="button" onclick=(newImg(),clickCounter(),changeImg())>images</button>
<div id="result"></div>
<script>
function newImg(){
var myArray = [
"img_1.jpg",
"img_2.jpg",
"img_3.jpg",
"img_4.jpg"
];
var imgNew = "https://example.com/"
var randomItem = myArray[Math.floor(Math.random()*myArray.length)];
document.getElementById("img_main").src = "https://example.com/" + randomItem ;
}
function clickCounter() {
if (typeof(Storage) !== "undefined") {
if (localStorage.clickcount) {
localStorage.clickcount = Number(localStorage.clickcount)+1;
} else {
localStorage.clickcount = 1;
}
function changeImg(){
if (localStorage.clickcount = 10,20) {
document.getElementById("ins_main").src = "https://example.com/pre_defined_img.jpg";
}
}
</script>
</body>
the way I see that...
by simply use of the modulo (finds the remainder after division)
you don't need to use an iframe, img element is enough.
use an IIFE. as closure method
file : "myScript.js"
const imgBox = (function()
{
const refURL = 'https://i.picsum.photos/id/'
, imgName = [ '251/300/500.jpg', '252/300/500.jpg', '253/300/500.jpg', '254/300/500.jpg'
, '255/300/500.jpg', '256/300/500.jpg', '257/300/500.jpg', '258/300/500.jpg'
, '259/300/500.jpg', '260/300/500.jpg', '261/300/500.jpg', '146/300/500.jpg'
, '263/300/500.jpg', '264/300/500.jpg', '265/300/500.jpg', '266/300/500.jpg'
, '267/300/500.jpg', '268/300/500.jpg', '269/300/500.jpg', '270/300/500.jpg'
, '271/300/500.jpg', '272/300/500.jpg', '273/300/500.jpg', '274/300/500.jpg'
]
, imgZero = '250/300/500.jpg'
, imgSiz = imgName.length
, imgMain = document.getElementById('img-main')
;
var imgNum = 0, randomI = 0;
const obj =
{ setNext()
{
if (!(++imgNum % 10)) // each 10 times
{
imgMain.src = refURL + imgZero
}
else
{
randomI = Math.floor(Math.random() * imgSiz)
imgMain.src = refURL + imgName[randomI]
}
return imgNum
}
}
return obj
})()
const btImg = document.getElementById('bt-img')
, imgCount = document.getElementById('img-count')
, banner = document.getElementById('my-banner')
;
btImg.onclick =evt=>
{
let counter = imgBox.setNext()
imgCount.textContent = counter
if (!(counter %50)) // each 50 times..
{
changeBanner()
}
}
// changing banner function...
function changeBanner()
{
//.....
// do what ever you want to change your banner
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<style>
img#img-main {
width: 300px;
height: 500px;
border: 1px solid grey;
padding: 2px;
}
</style>
</head>
<body>
<img id="img-main" src="https://i.picsum.photos/id/250/300/500.jpg" alt="" >
<p id="img-count">0</p>
<button id="bt-img">Image change</button>
<div id="my-banner">the banner</div>
<script src="myScript.js"></script>
</body>
</html>
Im working on an assignment for my javascript class, and I keep getting the error
fetch_page.js:109 Uncaught TypeError: Cannot read property 'addEventListener' of null
at addEventListeners (fetch_page.js:109)
at fetch_page.js:121
I'll be honost, I don't understand javascript for crap, but I'm forced to take this class for my network admin degree. Can anyone point out where I'm making this error?
window.addEventListener('DOMContentLoaded', (function() {
var contents;
var protocol;
var hostname;
var directory;
var file;
function parseBase() {
var pos, slashPos;
var remainder;
pos = BASE.indexOf('://');
protocol = BASE.substr(0, pos);
remainder = BASE.substr(pos + 3);
slashPos = remainder.indexOf('/');
if (slashPos === -1) {
hostname = remainder;
directory = "";
file = "";
} else {
hostname = remainder.substr(0, slashPos);
remainder = remainder.substr(slashPos + 1);
slashPos = remainder.lastIndexOf('/');
if (slashPos === -1) {
directory = "";
file = remainder;
} else {
directory = remainder.substr(0, slashPos);
file = remainder.substr(slashPos + 1);
}
}
console.log("protocol:", protocol);
console.log("hostname:", hostname);
console.log("directory:", directory);
console.log("file:", file);
}
function relativeToAbsolute(url) {
if (url.indexOf('://') > -1) { // http://somedomain.com/path/file.html
return url;
} else if (url[0] === '/') { // /path/file.html
return protocol + "://" + hostname + url;
} else { // path/file.html
if (directory === "") {
return protocol + "://" + hostname + "/" + url;
} else {
return protocol + "://" + hostname + "/" + directory + "/" + url;
}
}
}
function parsePage() {
var parser = new DOMParser();
contents = parser.parseFromString(atob(PAGE), "text/html");
console.log(contents);
}
function moveChildren(source, destination) {
while (source.childNodes.length > 0) {
var child = source.childNodes[0];
source.removeChild(child);
destination.appendChild(child);
}
}
function fixTags(tagName, attribute) {
var tags = contents.getElementsByTagName(tagName);
for (var counter = 0; counter < tags.length; counter++) {
var url = tags[counter].getAttribute(attribute);
if (url) {
tags[counter].setAttribute(attribute, relativeToAbsolute(url));
}
}
}
function fixRedirectedTags(tagName, attribute) {
var tags = contents.getElementsByTagName(tagName);
for (var counter = 0; counter < tags.length; counter++) {
var url = tags[counter].getAttribute(attribute);
if (url) {
tags[counter].setAttribute(attribute,
window.location.origin + window.location.pathname + '?url=' + encodeURIComponent(relativeToAbsolute(url)));
}
}
}
function fixURLs() {
fixTags('img', 'src');
fixTags('script', 'src');
fixTags('link', 'href');
fixRedirectedTags('a', 'href');
}
function moveContent() {
moveChildren(contents.head, document.head);
moveChildren(contents.body, document.getElementById('contents'));
}
function submit() {
console.log("submitted:", encodeURIComponent(document.getElementById('urlBox').value));
}
function addEventListeners() {
document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
if (event.keyCode == 13 || event.keyCode == 10) {
submit();
}
});
}
return function() {
parseBase();
parsePage();
fixURLs();
moveContent();
addEventListeners();
}
})())
body {
margin: 0px;
}
#searchBox {
background: black;
color: white;
width: 100%;
text-align: center;
vertical-align: middle;
padding: 10px;
}
#goButton {
background: red;
color: black;
padding: 4px
font-weight: bold;
font-family: Arial;
font-size: .75em;
vertical-align: middle;
cursor: pointer;
}
#urlBox {
width: 50%
}
#contents {
border: 1px solid black;
}
<?php
$url = isset ($_GET['url']) ? $_GET['url'] : "http://eloquentjavascript.net/";
$contents = base64_encode(mb_convert_encoding(file_get_contents($url), "HTML-ENTITIES","UTF-8"));
?>
<!doctype html>
<html>
<head>
<title>Fetch Page</title>
<link rel="stylesheet" href="fetch_page.css">
<script src="fetch_page.js"></script>
<script>
var BASE = "<?php echo $url; ?>";
var PAGE = "<?php echo $contents; ?>";
</script>
</head>
<body>
<div id="searchBox">Type a URL here: <input type="text" id=urlBox"> <span id="goButton">GO</span></div>
<div id="tocContainer">
<div id="toc">[toc goes here]</div>
<p id="contents">Hello World!</p>
<div id="contents"></div>
</body>
</html>
What does your error mean?
Uncaught TypeError: Cannot read property 'addEventListener' of null.
at addEventListeners
That boils down to:
You've tried to access the addEventListener property of something in the addEventListeners function, but that's null.
Take a look at addEventListeners:
document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
if (event.keyCode == 13 || event.keyCode == 10) {
submit();
}
});
One of the getElementsById calls has returned null, indicating that there's no such ID in your code.
After looking at the HTML, you can see that the problem is at the following place:
<input type="text" id=urlBox">
You're missing the opening quote at the ID, so really you've given your element the ID of urlBox" (you can omit quotes around a HTML attribute, but not recommended though).
That's why the JS can't find the element with ID urlBox
Just experienced something similar. Adding a defer to my script tag solved the issue:
<script src="fetch_page.js" defer></script>
Good luck! ~E
One of these two document.getElementById calls is returning null, because there's no element with that Id. You can add a breakpoint in the debug console in the code, or add a console.log to figure out exactly where the problem is occuring
document.getElementById('goButton').addEventListener('click', submit);
document.getElementById('urlBox').addEventListener('keydown', function(event) {
Apart from any typing error like eg. omitting quotes, try defer in the <script src ... line of the html code. I solved my problem in this way!
I had this problem too and I checked my code and everything was in other. I realized that it was where I positioned my script tag i.e the head of the html file so I then put it at the end of my body tag. I also found out that from one of the guys who answered this question that using "defer" makes it work no matter where the script tag is as long as it's inside the html tag.
Add window.onload = function() {<enter your javascript code here}; to your script. That easy.
I have a problem
this are my first steps in javascript and I'm trying to make a Javascript slide show.
I try to add a "slide in" "slide out" effect
But I don't know how I can do this.
I google about 2-3 hours but still no solution.
Please help me and give me some feedback please
Here is my code
<head>
<title>Test Slider</title>
</head>
<body>
<div id="slider" style="width: 400px; height: 200px;color: orange; font-weight: bold; font-size: 30px;font-family: sans-serif" onclick="javascript:superlink()" style="cursor:pointer;"></div>
<script type="text/javascript">
//Init//
var SlideDauer = 2000;
var ImgInX = 0;
var ImgInXposition = 0;
var background = 'url(http://www.flashforum.de/forum/customavatars/avatar47196_1.gif)';
var SldInX = 0;
var LinkInX = 0;
function superlink() {
if (!SliderKannEsLosGehen()) return false;
if (LinkInX >= SliderBilder.length) {
LinkInX = 0;
}
var Ziel = window.location.href = SliderLink[LinkInX];
++LinkInX;
}
var SliderBilder = new Array();
SliderBilder.push("http://ds.serving-sys.com/BurstingRes//Site-80313/Type-0/721dbabb-2dd5-4d92-9754-7db9c5888f48.jpg");
SliderBilder.push("http://bytes.com/images/bytes_logo_a4k80.gif");
SliderBilder.push("http://cdn.qservz.com/file/df8e9dcf202cfddedf6f2d4d77fcf07b.gif");
SliderBilder.push("http://ds.serving-sys.com/BurstingRes//Site-80313/Type-0/721dbabb-2dd5-4d92-9754-7db9c5888f48.jpg");
//SliderBilder.push("http://www.flashforum.de/forum/customavatars/avatar47196_1.gif");
var SliderTitle = new Array();
SliderTitle.push("");
SliderTitle.push("Title 1");
SliderTitle.push("Title 3");
SliderTitle.push("Title 4");
//SliderTitle.push("Title 5");
var SliderLink = new Array();
SliderLink.push("http://www.google.de");
SliderLink.push("http://spiegel.de");
SliderLink.push("http://bing.com");
SliderLink.push("http://youtube.com");
//SliderLink.push ("http://www.flashforum.de/forum/customavatars/avatar47196_1.gif");
function SliderKannEsLosGehen() {
if (SliderBilder.length < 2) return false;
return true;
if (SliderTitle.length < 2) return false;
return true;
}
//Run//
function SliderRun() {
if (!SliderKannEsLosGehen()) return false;
if (ImgInX >= SliderBilder.length) {
ImgInX = ImgInXposition;
}
if (SldInX >= SliderBilder.length) {
SldInX = 0;
}
document.getElementById("slider").style.backgroundImage = 'url(' + SliderBilder[ImgInX] + ')';
++ImgInX;
document.getElementById("slider").innerHTML = SliderTitle[SldInX];
++SldInX;
window.setTimeout("SliderRun()", SlideDauer);
}
window.setTimeout("SliderRun()", SlideDauer);
</script>
</body>
</html>
For effects i would look into JQuery and use the animate function. There is loads of fun to be had with this as long as you have an understanding of css.
I have seen this jQuery syntax:
if($(element).is(':hover')) { do something}
Since I am not using jQuery, I am looking for the best way to do this in pure javascript.
I know I could keep a global variable and set/unset it using mouseover and mouseout, but I'm wondering if there is some way to inspect the element's native properties via the DOM instead? Maybe something like this:
if(element.style.className.hovered === true) {do something}
Also, it must be cross browser compatible.
Simply using element.matches(':hover') seems to work well for me, you can use a comprehensive polyfill for older browsers too: https://developer.mozilla.org/en-US/docs/Web/API/Element/matches
You can use querySelector for IE>=8:
const isHover = e => e.parentElement.querySelector(':hover') === e;
const myDiv = document.getElementById('mydiv');
document.addEventListener('mousemove', function checkHover() {
const hovered = isHover(myDiv);
if (hovered !== checkHover.hovered) {
console.log(hovered ? 'hovered' : 'not hovered');
checkHover.hovered = hovered;
}
});
.whyToCheckMe {position: absolute;left: 100px;top: 50px;}
<div id="mydiv">HoverMe
<div class="whyToCheckMe">Do I need to be checked too?</div>
</div>
to fallback I think it is ok #Kolink answer.
First you need to keep track of which elements are being hovered on. Here's one way of doing it:
(function() {
var matchfunc = null, prefixes = ["","ms","moz","webkit","o"], i, m;
for(i=0; i<prefixes.length; i++) {
m = prefixes[i]+(prefixes[i] ? "Matches" : "matches");
if( document.documentElement[m]) {matchfunc = m; break;}
m += "Selector";
if( document.documentElement[m]) {matchfunc = m; break;}
}
if( matchfunc) window.isHover = function(elem) {return elem[matchfunc](":hover");};
else {
window.onmouseover = function(e) {
e = e || window.event;
var t = e.srcElement || e.target;
while(t) {
t.hovering = true;
t = t.parentNode;
}
};
window.onmouseout = function(e) {
e = e || window.event;
var t = e.srcElement || e.target;
while(t) {
t.hovering = false;
t = t.parentNode;
}
};
window.isHover = function(elem) {return elem.hovering;};
}
})();
it occurred to me that one way to check if an element is being hovered over is to set an unused property in css :hover and then check if that property exists in javascript. its not a proper solution to the problem since it is not making use of a dom-native hover property, but it is the closest and most minimal solution i can think of.
<html>
<head>
<style type="text/css">
#hover_el
{
border: 0px solid blue;
height: 100px;
width: 100px;
background-color: blue;
}
#hover_el:hover
{
border: 0px dashed blue;
}
</style>
<script type='text/javascript'>
window.onload = function() {check_for_hover()};
function check_for_hover() {
var hover_element = document.getElementById('hover_el');
var hover_status = (getStyle(hover_element, 'border-style') === 'dashed') ? true : false;
document.getElementById('display').innerHTML = 'you are' + (hover_status ? '' : ' not') + ' hovering';
setTimeout(check_for_hover, 1000);
};
function getStyle(oElm, strCssRule) {
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle) {
strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
}
else if(oElm.currentStyle) {
strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1) {
return p1.toUpperCase();
});
strValue = oElm.currentStyle[strCssRule];
}
return strValue;
};
</script>
</head>
<body>
<div id='hover_el'>hover here</div>
<div id='display'></div>
</body>
</html>
(function getStyle thanks to JavaScript get Styles)
if anyone can think of a better css property to use as a flag than solid/dashed please let me know. preferably the property would be one which is rarely used and cannot be inherited.
EDIT: CSS variable are probably better to use to check this. E.g.
const fps = 60;
setInterval(function() {
if(getComputedStyle(document.getElementById('my-div')).getPropertyValue('--hovered') == 1) {
document.getElementById('result').innerHTML = 'Yes';
} else {
document.getElementById('result').innerHTML = 'No';
};
}, 1000 / fps);
#my-div {
--hovered:0;
color: black;
}
#my-div:hover {
--hovered:1;
color: red;
}
<!DOCTYPE html>
<html>
<head>
<title>Detect if div is hovered with JS, using CSS variables</title>
</head>
<body>
<div id="my-div">Am I hovered?</div>
<div id="result"></div>
</body>
</html>
You can use an if statement with a querySelector. If you add ":hover" to the end of the selector, it will only return the element if it is being hovered. This means you can test if it returns null. It is like the element.matches(":hover) solution above, but I have had more success with this version.
Here is an example:
if (document.querySelector("body > p:hover") != null) {
console.log("hovered");
}
You can put it in an interval to run the code every time you hover:
setInterval(() => {
if (document.querySelector("body > p:hover") != null) {
console.log("hovered");
}
}, 10);