I am trying to trigger an window open event such as "window.open" whenever the within the body of the document, the elements "P id" becomes true.
So when, within the body of the page, this ID happens to load:
<p id=newPlayListText>
"There is a new playlist that was sent to you, check it out here."
I can triggered the event of "window.open".
This is what i have and after inspecting it, its not flagging anything to debug and nothing happens...
//#test: check to see if the new playlist banner text pops up during ep.
window.onload = function () {
if(element.id = "nextPlaylistText") {
window.open("http://www.w3schools.com");
}
Please help
The window.onload hook is called when the page loads, but element is never defined. You'll need to assign the variable to element before using it:
var element = document.getElementById("newPlayListText");
There are two issues with your code. First as Litty correctly pointed out that element is never declared. Second you aren't comparing values within if block.
if(element.id = "nextPlaylistText") // required `===` or at-least `==`
P.S. some browsers may block this line window.open
window.onload = function() {
var p = document.getElementById('newPlayListText');
if (!p) {
alert('New playlist not found');
return;
}
var popup = window.open("http://www.w3schools.com");
if (!popup) {
alert('Kindly un-block/disable pop-up blocker');
return;
}
};
<p id="newPlayListText">There is a new playlist that was sent to you, check it out here.</p>
Related
I got a warning by my ad system provider about click fraud. No further info, all they are recommending is "hide the ads for users who click on ads too quickly'". I wrote a piece of JS script that hides all DIVs with ads for N seconds (using cookie) when clicked on, but this solution does not work as the "inner" content (with ads) is generated by an JS script that calls and renders the content from external server (as you would expect from an ad system). So, when one takes the cross-domain security into account it is kinda Catch 22. How can I detect a click inside a DIV (locally defined) of which content is rendered by an external JS and in iframe?
Example:
<div class="ad-class"> <!-- locally defined div -->
<div id="my-id"> </div> <!-- identifies my ad in the provider's system -->
<script>
var foo = blah // declares the ad dimensions and stuff
// and renders the contextual ad in #my-id DIV
</script>
</div>
Were it all local, solution would be easy as the internal div would inherit the parent class ("ad-class"). In case of cross-domain, this is not valid. Any tips, dudes?
You cannot detect click events in cross-domain iframe.
That put, you might have one bad option:
One of the nearest things you can do is detect that the focus moved from your window to the iframe:
window.focus(); //force focus on the currenct window;
window.addEventListener('blur', function(e){
if(document.activeElement == document.querySelector('iframe'))
{
alert('Focus Left Current Window and Moved to Iframe / Possible click!');
}
});
http://jsfiddle.net/wk1yv6q3/
However it's not reliable, loose focus does not mean a click, it could be user moving across the website using TAB.
Another problem is that, you only detect the first time focus is moved to the iframe, you do not know what user does in there, he can click a million times and you will never know.
Luizgrs inspired me this solution :
var clickIframe = window.setInterval(checkFocus, 100);
var i = 0;
function checkFocus() {
if(document.activeElement == document.getElementById("ifr")) {
console.log("clicked "+(i++));
window.focus();
}
}
<!DOCTYPE html>
<h2>Onclick event on iframe</h2>
<iframe src="https://www.brokenbrowser.com/" id="ifr"></iframe>
The function detect if the iframe has the focus, if yes, the user clicked into the iframe. We then give back the focus to our main windows, which allow us to find if the user click another time.
This trick has been usefull to me for a POC on a 2 step iframe click-jacking. Getting to know when the user clicked for the first time on the iframe allowed me to reorganize my different layers to keep the illusion perfect.
The approach #Luizgrs pointed out is very accurate, however I managed to indeed detect the click event using a variation of the method:
var iframeMouseOver = false;
$("YOUR_CONTAINER_ID")
.off("mouseover.iframe").on("mouseover.iframe", function() {
iframeMouseOver = true;
})
.off("mouseout.iframe").on("mouseout.iframe", function() {
iframeMouseOver = false;
});
$(window).off("blur.iframe").on("blur.iframe", function() {
if(iframeMouseOver){
$j("#os_top").click();
}
});
The above code works like a charm on desktop if you want to add mobile support you just need to use touch events touchstartand touchendevents to simulate the mouseover on mobile.
Source
Well, a while ago I found this plugin for WordPress. Obviously it does what I need -- just wondering how this guy made it to work, it does count clicks on Adsense iframe. I must have a closer look though I am not a PHP programmer. I program mainly in Python and need some solution of this kind for Django. If anyone can read the code easily, I would appreciate any help.
The plugin is searching first for any iframe wrapped by a previous specified class name.
The iframe id´s will be collected in a array and for everyone of these id´s an mouseover event will be created which fires the script which hides the class 'cfmonitor'. As a result the iframe containing ad is not visible anymore.
// IFRAME ACTION
function iframeAction () {
jq.each(jq.cfmonitor.iframes, function(index,element) {
frameID = jq(element).attr('id') || false;
if (frameID) initiateIframe(frameID);
//alert (frameID);
});
}
// INIT IFRAME
function initiateIframe(elementID) {
var element = document.getElementById(elementID);
// MOUSE IN && OUT
if (element) {
element.onmouseover = processMouseOver;
element.onmouseout = processMouseOut;
//console.log("mouse on out");
}
// CLICKS
if (typeof window.attachEvent !== 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener !== 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
// IFRAME CLICKS
function processIFrameClick() {
// ADD A CLICK
if(isOverIFrame) {
//addClick();
// Some logic here to hide the class 'cfmonitor'
//console.log("Go");
top.focus();
}
}
Check this it might help. You can not detect the click event when its cross browser.
window.focus();
window.addEventListener('blur', function(e){
if(document.activeElement == document.getElementById('Your iframe id'))
{
console.log('iframe click!');
}
});
I'm creating my own Safari Extension which inserts 2 buttons into my DOM to improve the user experience on some websites.
I created an Extension using Safari Extension Builder. I created a script called end.js which is loaded after every finished HTTP request. In this script I check my DOM if a specific element exists and insert my buttons next to this element.
The buttons are created like this:
var headerElements = window.document.getElementsByClassName("headers");
if (headerElements.length > 0) {
var header = headerElements[0];
if (header.getElementsByClassName("button1").length == 0) {
var div = window.document.createElement("div");
div.setAttribute("class", "buttons-div");
var button1 = window.document.createElement("button");
button1.setAttribute("class", "button1");
button1.setAttribute("style", "width: 150px;");
button1.innerHTML = "allen folgen";
button1.onclick = function() {
alert("click button1");
};
div.appendChild(button1);
header.appendChild(div);
}
}
As soon as I press the button only an error message is displayed on the console:
onclick — end.js (Zeile 27) TypeError: alert is not a function. (In 'alert("button pressed")', 'alert' is undefined)
Why do I have access to all functions "outside" the onclick event, but as soon as the function is entered I can't access any of those functions? Even if I create my own function
function click() {
alert("test");
}
and set the button's onclick to this:
button1.onclick = click;
I get the same error message.
What am I doing wrong?
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.
I know this is an unusual question. No, this is not a typo.
I'm looking to open the same page on a new window. And with that new window, I would like to have cross javascript manipulation. Meaning that the new Window can manipulate the old window, and vice versa; From JavaScript (Can be jQuery) to the complete DOM. Plus synchronous scrolling
Thanks a lot!
Here:
// you use a regular window.open()
var w = window.open(window.location.href);
// the variable w now contains a reference to the newly opened window.
// from the newly opened window use window.opener :
window.opener.alert("Called in parent window.");
Ok. Finally found the true answer to all of my headaches.
I'll explain what is the best way to communicate between a parent window and a child window from the same page. This logic can be tweaked for different pages (but from the same host).
Used: JavaScript + PHP
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
<!--
var window_ = null;
var n = false; //Variable n
<?php
if(isset($_GET['n'])) //This will make the n variable go true if
//'?n' (without quotes) is found in the URL. Meaning, that the child exists
{
print('n = true;');
}
?>
function openChildWindow() //function which opens the child window.
{
if (window_ != null) //This will check if the window is opened
{
if ( window_.closed == false ) //if the window is opened, a.k.a is not closed
window_.close(); // close the window
window_ = null; // and nullify the variable, so it can be reopened if desired.
}
else
{
window_ = window.open(window.location.href+'?n'); //This is the tricky part.
/*Assign the window.location.href so it will open a new window with the same page
BUT assign it the n variable, so the GET function will receive it, and set n to true.
*/
window_.focus();
}
// Need to call on a delay to allow
// the child window to fully load...
}
function callChildWindowFunction()
{
if ( (window_ != null) && (window_.closed == false) )
{
window_.shout('bearl');
}
}
// -->
function shout(val)
{
alert(val);
}
$(document).ready(function(e) {
/*Wait for the document to load, so you can check if the variable n is true,
which means that **IT IS** the child window and it has been loaded completely. Meaning
that you can finally manipulate the child window with the parent document*/
if(n == true)
{
window.opener.callChildWindowFunction(); //Call the parent telling it "I'm ready"
}
});
</script>
<input type="button" value="Blear" onClick="openChildWindow();">
Now, explaining the code.
The trick here is to create an "artificial switch" which will tell the browser which page is the parent, and which is the child.
The one who does this, is the variable n. By assigning it a false value, I'm telling it is the parent who has been loaded and not the child.
When the child window is opened, (please see the openChildWindow() function), it will verify if the window has been opened so it can close/open it, according to the situation.
If the window is opened, it will assign the EXACT URL plus the ?n variable which will help PHP to identify that it is the child window.
At the bottom of the opened page, after the document has been loaded, n will be true, so it will call the parent through the window.opener function. This will trigger a function, that will trigger the child's function (shout(val)).
You can also do this with two different pages.
Create a Page "A.html" and a Page "B.html" (Without quotes).
Page A will get the following code:
<script type="text/javascript">
<!--
var window_ = null;
function openChildWindow()
{
if ( (window_ != null))
{
if ( window_.closed == false )
window_.close();
window_ = null;
}
var windowUrl = 'B.html';
window_ = window.open(windowUrl);
window_.focus();
}
function callChildWindowFunction()
{
if ( (window_ != null) && (window_.closed == false) )
{
window_.shout('bearl');
}
}
// -->
</script>
<input type="button" value="Blear" onClick="openChildWindow();">
Page B will get this
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function shout(val)
{
alert(val);
}
$(document).ready(function(e) {
{
window.opener.callChildWindowFunction();
}
});
</script>
Note that the mechanics are the same. The only thing that there is no need for an "artificial switch" because the pages are different.
Just assign the page B you want to create a $(document).ready() function to verify it has loaded completely, and call the parent through the window.opener function so it can start calling the child.
If you've found a better way to do this, then go ahead and show me. setTimeOut, setInterval functions did not work because the code pre-executed before the time was out (Opera). Furthermore, this will assure you that the document was 100% loaded, and the code will not break if the user has slowpoke Internet connection.
Okay i know this has been asked a lot but it seems that none of the solutions actually work for me. Here's the situation. I have a webpage that i need to add to an existing site, this site uses a master page which i can not touch. This limits me to using javascripts window.onload because i do not have access to the body tag.
On my page i have linked my external .js file in the head beneath every other external file. Here is an example of what my .js file looks like.
var myobj = null;
(5 or so functions that work properly. Mainly just toggles that show and hide divs. none touch the onload)
function load(){
myobj = document.getElementById("my_element");
alert("test");
}
window.onload = load;
Tried this and the load function never fires as i never get the alert. I've tried commenting out the first line in the load function and only haven't the alert and still nothing. Looking around i also found another way to do it that i tried without success. Everything else is the same except i removed the window.load and added this.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(load);
addLoadEvent(function () {
/* more code to run on page load */
alert("hello2");
});
In this function, neither of the alerts fire. I have also tried placing an alert outside of a function, that one does work.
The browsers i am using are IE 8.0.7600.16385 and Chrome 21.0.1180.60
Let me know if you need more information.
Oh and as a side note, i cannot use jquery or any other javascript library as we are trying to keep this as light as possible. This page also must work in IE8, that is the businesses only supported browser at the moment. It would be nice if it worked in Chrome as well.
EDIT
In case i'm going about this completely the wrong way, what i am trying to do is keep track of the last element i have. I essentially have a page with 2 columns, left side is a menu and right is content. The content is all placed in div's with only one category showing at a time. The way it is supposed to work is when clicking on the menu category it hides the previous content and shows the new content.
I have set my content class to display: none; and have the start_content ID set to display: block;. What the Javascript is supposed to do is initialize my global with the start_content object. When clicking in the menu it calls a function that does an obj.style.display = 'none' and then sets the new obj to display = 'block'. It then takes the new obj and places it in my global variable to be changed on the next menu click.
here's an example without any of the onload functions
var prevContent = document.getElementById("start_content");
function toggle(id) {
prevContent.style.display = "none";
var content = document.getElementById(id);
content.style.display = "block";
prevContent = content;
}
The problem with this is that prevContent is unidentified when it enters the toggle function. I had assumed this was because i am linking this .js file in the head and so the page hasn't loaded my start_content yet which is why i had changed it to declaring the global as a null and then setting up a window.onload to set the appropriate value after it is created.
Adding "Defer" to the script tag in the head ended up doing the trick.