IFrame Cross Domain Click Tracking - javascript

The Below code was able to track the clicks on iframe but i was not able to know click (right/left/middle) ???
<script>
var isOverIFrame = false;
function processMouseOut() {
isOverIFrame = false;
top.focus();
}
function processMouseOver() {
isOverIFrame = true;
}
function processIFrameClick() {
if (isOverIFrame) {
//was clicked
console.log('tracking');
}
}
function init() {
var element = document.getElementsByTagName("iframe");
for (var i = 0; i < element.length; i++) {
element[i].onmouseover = processMouseOver;
element[i].onmouseout = processMouseOut;
}
if (typeof window.attachEvent != 'undefined') {
top.attachEvent('onblur', processIFrameClick);
}
else if (typeof window.addEventListener != 'undefined') {
top.addEventListener('blur', processIFrameClick, false);
}
}
</script>
<iframe src="http://google.com"></iframe>
<script>init();</script>
can some one help me on this issue...

You can't follow the clicks happening inside the iFrame, a policy put in place to prevent the exact kind of behavior you're trying to achieve.
What you're trying to do could be construed as "clickjacking."

Related

cefsharp cannot play audio by javascript

I am writing a dictionary program using CefSharp by C#. When the dictionary page(i.e.[Longman-love][1]) is loaded I want it could play its pronounce automatically(by clicking the pronouce icon using JavaScript). Here are related codes:
C# part:
browser.FrameLoadEnd += (sender, args) =>
{
//Wait for the MainFrame to finish loading
if (args.Frame.IsMain)
{
browser.ExecuteScriptAsync("document.getElementsByClassName('amefile')[0].click();");
}
};
JavaScript part(I copyed it from web and added some 'alert's for debugging the program):
$(document).ready(function(){
var audio = null;
$(".speaker").click(function(){
alert('x');
var src_mp3 = $(this).attr("data-src-mp3");
if (supportAudioHtml5())
playHtml5(src_mp3);
else if (supportAudioFlash())
playFlash(src_mp3);
else
playRaw(src_mp3);
});
function supportAudioHtml5(){
var audioTag = document.createElement('audio');
try {
return ( !!(audioTag.canPlayType)
&& (audioTag.canPlayType("audio/mpeg") != "no" && audioTag.canPlayType("audio/mpeg") != "" ) );
} catch(e){
return false;
}
}
function supportAudioFlash() {
var flashinstalled = 0;
var flashversion = 0;
if (navigator.plugins && navigator.plugins.length){
x = navigator.plugins["Shockwave Flash"];
if (x){
flashinstalled = 2;
if (x.description) {
y = x.description;
flashversion = y.charAt(y.indexOf('.')-1);
}
} else {
flashinstalled = 1;
}
if (navigator.plugins["Shockwave Flash 2.0"]){
flashinstalled = 2;
flashversion = 2;
}
} else if (navigator.mimeTypes && navigator.mimeTypes.length){
x = navigator.mimeTypes['application/x-shockwave-flash'];
if (x && x.enabledPlugin)
flashinstalled = 2;
else
flashinstalled = 1;
} else {
for(var i=7; i>0; i--){
flashVersion = 0;
try{
var flash = new ActiveXObject("ShockwaveFlash.ShockwaveFlash." + i);
flashVersion = i;
return (flashVersion > 0);
} catch(e){}
}
}
return (flashinstalled > 0);
}
function playHtml5(src_mp3) {
alert('html5');
if(audio != null){
if(!audio.ended){
audio.pause();
if(audio.currentTime > 0) audio.currentTime = 0;
}
}
//use appropriate source
audio = new Audio("");
if (audio.canPlayType("audio/mpeg") != "no" && audio.canPlayType("audio/mpeg") != "")
audio = new Audio(src_mp3);
//play
audio.addEventListener("error", function(e){alert("Apologies, the sound is not available.");});
alert('will play');
audio.play();
}
The last alert sentence alert('will play'); showed but I could not hear anything. However,when I clicked the audio icon directly in the CefSharp browser, it could play the pronounce. How could I fix this problem? I am not a native English speaker, I hope you can understand me. Many thanks!
[1]: https://www.ldoceonline.com/dictionary/love
This problem occured beacause Google had changed autoplay policy for audios and videos. You can active auto play by adding a commandline flag --autoplay-policy=no-user-gesture-required. In my case:
public BrowserForm()
{
InitializeComponent();
var settings = new CefSettings();
settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
settings.CefCommandLineArgs["autoplay-policy"] = "no-user-gesture-required";//Add this statement solve the problem
Cef.Initialize(settings);
//some other statements
}
If anyone happens to meet the same problem in the futrue, I hope this will help you!
Here is a related topic.

Animate CC HTML5 - toggle fullscreen

I have this code (below) on a buton to force my HTML5 game to fullscreen, but I'd like to have it turn back also with the button - right now it only works using ESC key. Is it possbile?
this.fsbtn.addEventListener("click", doFullscreen);
function doFullscreen() {
var i;
var elem = document.getElementById("animation_container");
var fs = ["requestFullscreen", "webkitRequestFullscreen", "mozRequestFullScreen", "msRequestFullscreen"];
for (i = 0; i < 4; i++) {
if (elem[fs[i]]) {
elem[fs[i]]();
break;
}
}
}
Sure it's possible. Change your doFullscreen function to a toggle one that checks if it's fullscreen or not:
function toggleFullscreen(event) {
var element = document.body;
if (event instanceof HTMLElement) {
element = event;
}
var isFullscreen = document.webkitIsFullScreen || document.mozFullScreen || false;
element.requestFullScreen = element.requestFullScreen || element.webkitRequestFullScreen || element.mozRequestFullScreen || function () {
return false;
};
document.cancelFullScreen = document.cancelFullScreen || document.webkitCancelFullScreen || document.mozCancelFullScreen || function () {
return false;
};
isFullscreen ? document.cancelFullScreen() : element.requestFullScreen();
}
Read the documentation here for fullscreen API
You can exit from fullscreen mode using functions listed below(for more read documentation)
In JS/HTML code you can add button with absolute position and high z-index. Write new click listener for added button and run cancelFullscreen function, that's all.
Example JS function for FullScreen mode:
function toggleFullScreen() {
if (!document.mozFullScreen && !document.webkitFullScreen) {
if (videoElement.mozRequestFullScreen) {
videoElement.mozRequestFullScreen();
} else {
videoElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.mozCancelFullScreen) {
videoElement.mozCancelFullScreen();
} else {
videoElement.webkitCancelFullScreen();
}
}
}
Working example you can see here: https://developer.mozilla.org/samples/domref/fullscreen.html

how do I hide an element in javascript if localstorage variable is true

I'm trying to hide a video when the page loads and keep the video shown after any link is pressed
this is my current code
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if(localStorage !== 'undefined')
{
console.log("localStorage exists")
if(localStorage["vv"] == false)
{
videoplayer.style.display = "none";
localStorage["vv"] = false;
}
else
{
for( i=0; i<links.length; i++ )
{
links[i].onclick = function()
{
localStorage["vv"] = true;
videoplayer.style.display = "block";
console.log(localStorage["vv"]);
}
}
}
}
else
{
localStorage["vv"] == false;
}
localStorage only holds strings. localStorage["vv"] = false; stores the string "false", which is not falsy.
Normally I store JSON and parse it. That's probably overkill here, though, just store "Y" or "N" as the flag and check that:
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if (typeof localStorage !== 'undefined')
// ^^^^^^ Note 2
{
console.log("localStorage exists")
if(localStorage["vv"] == "N")
{
videoplayer.style.display = "none";
// No need, it's already stored - localStorage["vv"] = false;
}
else
{
for( var i=0; i<links.length; i++ )
// ^^^^---- Note 1
{
links[i].onclick = function()
{
localStorage["vv"] = "Y";
videoplayer.style.display = "block";
}
}
}
}
/* You don't want this, it'll throw an error, since we know `localStorage` is falsy
else
{
localStorage["vv"] == false;
}
*/
However, nothing in the logic reasonably sets localStorage["vv"] to "N" (the one assignment that was there was in a branch where it's already there). You'll need to add something to set it, unless you want to default to hiding the video player and only show it when localStorage["vv"] is "Y" (or if local storage isn't accessible).
For instance, this hides the player and only shows it if the flag is "Y" on load or one of those links is clicked:
var videoplayer = document.getElementById("videoplayerlayer");
var links = document.getElementsByTagName("a");
if (typeof localStorage !== "undefined") {
if (localStorage.vv !== "Y") {
videoplayer.style.display = "none";
}
for (var i = 0; i < links.length; i++)
{
links[i].onclick = function()
{
localStorage["vv"] = "Y";
videoplayer.style.display = "block";
};
}
}
Note 1: Your code was falling prey to The Horror of Implicit Globals (that's a post on my anemic little blog). Be sure to declare your variables. See the "Note" comment above.
Note 2: Your check for whether you can use local storage was incorrect. I've updated it to what you probably meant above, but see see here for more thorough checks you'll want to use.
Note 3: I would recommend using modern event handling rather than setting onclick.
Below code can help you
$get('<%= AnchorId.ClientID %>').click(function(){
if(localStorage !== 'undefined'){
if(localStorage == false)
{
$get('<%= videoplayerlayer.ClientID %>').hide();
localStorage["vv"] = false;
}
else
{
$get('<%= videoplayerlayer.ClientID %>').show()
localStorage["vv"] = true;
}
}
});

Javascript - Display div

I need to check onload if an anchor is within the URL to open a tab if required. The problem is that if a user opens a tab before the onload function gets fired, the tab gets closed and the user needs to open it again.
How to fix that?
HTML:
<body onload="checkurl()">
JS:
function checkurl(){
if (window.location.hash == '#about')
{
showhide('secabout');
}
else if (window.location.hash == '#contact')
{
showhide('seccontact');
}
}
JS function:
var divState = {};
function showhide(id) {
if (document.getElementById) {
var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
for (var div in divState){
if (divState[div] && div != id){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
}
Thanks.
Uli
I'm pretty sure that <script> tags inside of <head> execute right away before onload() so try that.
You can call the function with an extra parameter to make sure will show in your load function.
Then check on a global initialized variable to check if the function has already been executed by user when running from the checkurl function. This is required if the user clicks on a different tab than the one specified in the URL.
Also you need to check on divState[id] instead of divid.style.display == 'block' when updating divid.style.display at bottom.
function checkurl(){
if (window.location.hash == '#about')
{
showhide('secabout', true);
}
else if (window.location.hash == '#contact')
{
showhide('seccontact', true);
}
}
var divState = {};
var initialized = false;
function showhide(id, initialize) {
if(initialized && initialize) return;
initialized = true;
if (document.getElementById) {
var divid = document.getElementById(id);
divState[id] = (divState[id]) ? false : true;
for (var div in divState){
if (divState[div] && div != id){
document.getElementById(div).style.display = 'none';
divState[div] = false;
}
}
if(initialize){
divid.style.display = 'block';
} else {
divid.style.display = (divState[id] ? 'block' : 'none');
}
}
}

ajax hidding div problem in IE

I have a javascript page which checks an email and username, this works fine in every browser but Internet Explorer. The div box where errors are shown should be hidden unless an error is given e.g. username taken or invalid email.
If the email gets an error this is shown in the div tag, but doesnt work for username (in all browsers)
below is my code:
<script type="text/javascript">
var usernameok;
var emailok;
function checksubmit()
{
if (usernameok && emailok) {
document.getElementById("button").disabled = false;
} else {
document.getElementById("button").disabled = true;
}
}
function username(username)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Username Ok") >= 0) {
usernameok = true;
} else {
usernameok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
user_url = "check_username.php?username=" + username.value;
httpxml.open("GET", user_url, true);
httpxml.send(null);
}
function email(email)
{
make_request();
function stateck()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
emailok = true;
} else {
emailok = false;
}
checkCanSubmit();
}
}
httpxml.onreadystatechange = stateck;
email_url = "check_email.php?email=" + email.value;
httpxml.open("GET", email_url, true);
httpxml.send(null);
}
</script>
I see your function stateck() is the return function from the HTTP request. However, you are defining it within another function. Not as an anonymous function, but just as a function within another function.
I see what you're doing now...ok, try this instead:
httpxml.onreadystatechange = function()
{
if (httpxml.readyState == 4) {
if (httpxml.responseText.indexOf("Email Ok") >= 0) {
document.getElementById("email").style.backgroundColor = "green";
document.getElementById("email").style.color = "white";
document.getElementById("email_div").style.display = 'none';
emailok = true;
} else {
document.getElementById("email").style.backgroundColor = "red";
document.getElementById("email_div").innerHTML=httpxml.responseText;
emailok = false;
}
checkCanSubmit();
}
};
Do you need to set your initial state to display: none? I think IE may initialize the divs with a non-0 height whereas the divs may be technically visible in other browsers but too short to see.
Edit:
Okay I think I misunderstood your question. Your problem is not with hiding the divs but with displaying errors for the username.
Nothing obvious jumps out at me. Try stepping through the code using VS or VWDE:
http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/

Categories