When I use new XMLHttpRequest in a function all page reload - javascript

I'm trying a week to find a way for the following problem.
I have a 1.php file
//bowser.js And fingerprint2.js are included I ignored them here
function HttpRequest(e) {
var i = !1;
i || "undefined" == typeof XMLHttpRequest || (i = new XMLHttpRequest), i && (i.open("GET", e, !1), i.send(null), embedpage(i))
}
function embedpage(e) {
(-1 == window.location.href.indexOf("http") || 200 == e.status) && 0 != e.responseText && document.write(e.responseText)
}
browser = bowser.name;
browserv = bowser.version;
bowser.windows ? os = "windows" : bowser.mac ? os = "mac" : bowser.linux ? os = "linux" : bowser.android ? os = "android" : bowser.ios ? os = "ios" : bowser.windowsphone ? os = "windowsphone" : bowser.chromeos ? os = "chromeos" : bowser.blackberry ? os = "blackberry" : bowser.firefoxos ? os = "firefoxos" : bowser.webos ? os = "webos" : bowser.tizen ? os = "tizen" : bowser.bada ? os = "bada" : bowser.sailfish && (os = "sailfish");
new Fingerprint2().get(function(result) {
url = 'http://gotoo.cf/2.php?tag=<?php echo $_GET["tag"] ?>&browser=' + browser + '&bv=' + browserv + '&os=' + os + '&secure=' + result;
HttpRequest(url);
});
2.php make html to show banners
when I use it in my blog by:
<script type="text/javascript" src="http://gotoo.cf/1.php?tag=6&width=120&height=240"></script>
it reload all page.
you can see there
http://adseo.blogfa.com/
but when I use HttpRequest(url);out of new Fingerprint2().get(function(result) { it works perfectly.
but the big problem is url var.( because ir can not be accessible out of function)
global var and cookie does not work because Fingerprint2().get(...) is asynchronous.
I want to know why HttpRequest(url); treat like that?
and how to store fingerprint2 result like function and use it whereever I want.
Or some method that you understand.

The problem is this here:
document.write(e.responseText)
The document.write will make the browser create a new document and then insert the passed text replacing all current content of the page. Instead, you need to tell the browser to insert the text into a specific part of the already existing document.
For example:
document.body.insertAdjacentHTML('afterbegin', e.responseText)
will insert the banner at the beginning of the page. In reality, you would want to use a more specific place inside the page. Use a div with a specific id as a placeholder and then replace the content of this div with the text retrieved via the asynchronous HTTP call.
Some more explanations:
When JavaScript code uses document.write() while the page is still being loaded, the content will be written at the current position of the currently loaded document. However, since you execute your code asynchronously using Fingerprint2.get(), the code is executed after the page has finished loading and document.write() will then lead to the browser starting with a new document.
From the documentation:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
How to solve your dilemma:
In your code, first add a div with a random unique identifier to the document using document.write. Then, in the callback function, that is called from Fingerprint2.get(), add the content into that div.
See the following example set of files that show the mechanism:
A.html
<html>
<body>
<script src="Banner.js"></script>
<div>Static Content</div>
<script src="Banner.js"></script>
</body>
</html>
B.html
<div>
Some Banner!
</div>
Banner.js
// Note that HttpRequest and embedpage are declared inside insertBanner
// so that they can access the aRandomName parameter
function insertBanner(aRandomName)
{
// First add a placeholder div with the given random name
document.write('<div id="' + aRandomName + '"></div>');
// Then asynchronously call HttpRequest()
// We use setTimeout where then FingerPrint2.get() would be used
url = "B.html";
setTimeout(
function()
{
HttpRequest(url);
}
, 100
);
function HttpRequest(e)
{
i = new XMLHttpRequest;
i.onreadystatechange = embedpage;
i.open("GET", e, true); // Use HttpRequest asynchronously to not block browser
i.send();
}
function embedpage(e)
{
if(this.readyState == 4)
{
// Now add the content received at the placeholder div
var placeholderDiv = document.getElementById(aRandomName);
placeholderDiv.innerHTML = this.responseText;
}
}
}
// First get a random name for the banner div
var randomName = 'GotooCF' + makeid();
// Now call the banner using the random name
insertBanner(randomName);
// makeid() Taken from http://stackoverflow.com/questions/1349404/generate-random-string-characters-in-javascript
function makeid()
{
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for( var i=0; i < 5; i++ )
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}

As NineyBerry said, the main problem is document.write()
so I used :
document.write=function(s){
var scripts = document.getElementsByTagName('script');
var lastScript = scripts[scripts.length-1];
lastScript.insertAdjacentHTML("beforebegin", s);
}
In all browser except Firefox it works.
But still need to be modifiled,
I think we should make a new document.write function for these situations.
thanks

Related

where is showing conversation value

THis topic is abouton google add word (conversation)
Below is my conversation setup screenshot
http://nimb.ws/alycTQ
Below is my code that was putted on body tag
<script type="text/javascript">
/* <![CDATA[ */
function GoogleFormTracker()
{
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = 949468534;
w.google_conversion_label = "9xLwCK7rm3IQ9vrexAM";
w.google_conversion_value = 1;
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
GoogleFormTracker() fired on footer when site is load.
And also i verified my code on tag manager chrome addons(No error showing there).
but i don't know where to showing me how many time this function is fired ?
let me know any mistake in my code or where is showing tracking value in add word (with screenshot and step by step).
Thanks
In google add word account follow below step
Tool->Attribution
In Attribution available you conversation value.
I hope u need like above
"but i don't know where to showing me how many time this function is fired". Not entirely sure I understand, but perhaps you just need to put a console.log('marco'); inside the function and view the browser console (ctrl + shift + i) to see how many times the function is called?

Reload Parent Window without POST

I am trying to reload a parent window (same domain) with javascript from within an iframe.
window.parent.location.href = window.parent.location.href;
does not work here for some reason (no javascript errors).
I don't believe it is a problem with same origin policy, as the following works:
window.parent.location.reload();
The problem with this option is if the last request was a POST, it gets reloaded as POST.
Any ideas why the first option wouldn't work? Otherwise, is there another method that will reload the page without resubmitting any form data (e.g. perform a fresh GET request to the parent page URL)?
I have also tried:
top.frames.location.href = top.frames.location.href;
window.opener.location.href = window.opener.location.href
and various other iterations.
I tried this code:
window.location.href = window.location.href;
in an ordinary page (no frames) and it had no effect either. The browser must detect that it is the same URL being displayed and conclude that no action needs to be taken.
What you can do is add a dummy GET parameter and change it to force the browser to reload. The first load might look like this (with POST data included, not shown here of course):
http://www.example.com/page.html?a=1&b=2&dummy=32843493294348
Then to reload:
var dummy = Math.floor(Math.random() * 100000000000000);
window.parent.location.href = window.parent.location.href.replace(/dummy=[0-9]+/, "dummy=" + dummy);
Phari's answer worked for me, with a few adjustments to fit my use case:
var rdm = Math.floor(Math.random() * 100000000000000);
var url = window.parent.location.href;
if (url.indexOf("rdm") > 0) {
window.parent.location.href = url.replace(/rdm=[0-9]+/, "rdm=" + rdm);
} else {
var hsh = "";
if (url.indexOf("#") > 0) {
hash = "#" + url.split('#')[1];
url = url.split('#')[0];
}
if (url.indexOf("?") > 0) {
url = url + "&rdm=" + rdm + hsh;
} else {
url = url + "?rdm=" + rdm + hsh;
}
window.parent.location.href = url;
}
I'm sure this could be more efficient, but works ok.

Safari print with Javascript produces blank when printing an Iframe

I have read up on all issues regarding Safari and blank printing. It seems that a white flash happens, re-rendering the page, and content of the iframe is lost before a print dialog can grab it.
Here is my javascript - It works in all browsers except safari. It brings up the dialog, but prints a blank page.
function PrintPopupCode(id) {
framedoc = document;
var popupFrame = $(framedoc).find("#" + id + '\\!PopupFrame');
var icontentWindow = popupFrame[0].contentWindow || popupFrame[0].contentDocument;
icontentWindow.focus();
icontentWindow.print();
}
function PrintPopup(id) {
setTimeout(function () { PrintPopupCode(id) }, 3000);
}
I have set a timeout, i previously read it would help if the transfer of content took sometime, but it has not helped.
I have also tried with printElement() function on the icontentWindow variable, but it does not support this method.
Print Element Method
This is all in a .js file, and not on the page. I have tried on the page, but the same thing happens.
Help?
Maybe you should try this:
function PrintPopupCode(id) {
framedoc = document;
var popupFrame = $(framedoc).find("#" + id + '\\!PopupFrame');
var icontentWindow = popupFrame[0].contentWindow || popupFrame[0].contentDocument;
icontentWindow.focus();
setTimeout(icontentWindow.print, 3000);
}
function PrintPopup(id) {
PrintPopupCode(id);
}

Javascript from file gives Uncaught ReferenceError

I am trying to dynamically adjust the height of an iFrame on a web page depending on the content within the iFrame via some JavaScript.
My problem is when I have the script directly on the page in a <script> tag it works fine. When I stuff the code in to a separate js file and link to it- it doesn't work!
<iframe id='StatusModule' onload='FrameManager.registerFrame(this)' src='http://randomdomain.dk/StatusModule.aspx'></iframe>
<script type='text/javascript' src='http://randomdomain.dk/FrameManager.js'></script>
It gives me the error:
Uncaught ReferenceError: FrameManager is not defined
Can this really be true? Has it something to do with the page life cycle?
Ps. I guess the JavaScript code is irrelevant, as we not it works.
UPDATE: I think this might have something to do with secure http (https) and the different browsers in some weird way. I noticed that the script actually worked in Firefox. Or rather I'm not sure if its the script, or just Firefox's functionality that resizes iframes automatically depending on the content. It doesn't give me any error though.
If I then add https to the script url reference, the scripts work in IE and Chrome - but not in Firefox. Function reference error! This just got weird!
UPDATE #2: Its not a Firefox function that resizes the iframe. Its the actual script that works (without https).
UPDATE #3: The JavaScript. Works fine if I put it directly into a script tag.
var FrameManager = {
currentFrameId: '',
currentFrameHeight: 0,
lastFrameId: '',
lastFrameHeight: 0,
resizeTimerId: null,
init: function () {
if (FrameManager.resizeTimerId == null) {
FrameManager.resizeTimerId = window.setInterval(FrameManager.resizeFrames, 0);
}
},
resizeFrames: function () {
FrameManager.retrieveFrameIdAndHeight();
if ((FrameManager.currentFrameId != FrameManager.lastFrameId) || (FrameManager.currentFrameHeight != FrameManager.lastFrameHeight)) {
var iframe = document.getElementById(FrameManager.currentFrameId.toString());
if (iframe == null) return;
iframe.style.height = FrameManager.currentFrameHeight.toString() + "px";
FrameManager.lastFrameId = FrameManager.currentFrameId;
FrameManager.lastFrameHeight = FrameManager.currentFrameHeight;
window.location.hash = '';
}
},
retrieveFrameIdAndHeight: function () {
if (window.location.hash.length == 0) return;
var hashValue = window.location.hash.substring(1);
if ((hashValue == null) || (hashValue.length == 0)) return;
var pairs = hashValue.split('&');
if ((pairs != null) && (pairs.length > 0)) {
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if ((pair != null) && (pair.length > 0)) {
if (pair[0] == 'frameId') {
if ((pair[1] != null) && (pair[1].length > 0)) {
FrameManager.currentFrameId = pair[1];
}
} else if (pair[0] == 'height') {
var height = parseInt(pair[1]);
if (!isNaN(height)) {
FrameManager.currentFrameHeight = height;
//FrameManager.currentFrameHeight += 5;
}
}
}
}
}
},
registerFrame: function (frame) {
var currentLocation = location.href;
var hashIndex = currentLocation.indexOf('#');
if (hashIndex > -1) {
currentLocation = currentLocation.substring(0, hashIndex);
}
frame.contentWindow.location = frame.src + '&frameId=' + frame.id + '#' + currentLocation;
}
};
window.setTimeout(FrameManager.init, 0);
UPDATE #4: Alright I did as ShadowWizard and TheZuck suggested:
<script type="text/javascript">
var iframe = document.createElement("iframe");
iframe.src = "http://www.randomdomain.dk/StatusWebModule.aspx";
iframe.width = '100%';
iframe.id = 'StatusModule';
iframe.scrolling = 'no';
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
FrameManager.registerFrame(iframe);
});
} else {
iframe.onload = function () {
FrameManager.registerFrame(iframe);
};
}
document.getElementById('framecontainer').appendChild(iframe);
</script>
With HTTP as URL its work on IE and Firefox - not Chrome. If I set it to HTTPS it works on Chrome and IE - Not Firefox. Same error:
"ReferenceError: FrameManager is not defined".
What is going on here?
a couple of things:
I would bet on a race condition when you have two independent
resources which are supposed to be loaded concurrently. You can
easily check this by writing to log (or to document, whichever works
for you) when both finish loading (i.e. add a little script in the
iframe to dynamically add the time to the content or write to log if
you're using chrome, do that in the external script file as well,
and see if they post the time in a specific order when this fails). In your case, if the script appears before the iframe, and you don't mark it as async, it should be loaded before the iframe is fetched, so it would seem strange for the iframe not to find it due to a race condition. I would bet on (3) in that case.
Assuming there is such an issue (and if there isn't now, when you go
out into the real world it will be), a better way to do this is to
make sure both behave well in case the other loads first. In your
case, I would tell the iframe to add itself to a local variable
independent of the script, and would tell the script to check if the
iframe registered when it loads, and after that in recurring
intervals until it finds the iframe.
If the page the script is loaded into is not in the same domain
as the iframe (note that it doesn't matter where the script comes
from, it only matters what the page's domain is), (or even the same
protocol as someone mentioned here), you will not be able to access
the content so you won't be able to resize according to what the
content is. I'm not sure about the onload method, if it's considered part of the wrapping page or part of the internal iframe.
Check out this question, it sounds relevant to your case:
There's also an interesting article here about this.
I think that your frame is loaded before the script, so "FrameManager" does not exist yet when the iframe has finished loading.

Automatically reload an iframe if source page changes

I don't know what's wrong with my code, even if I change the content of the target file it still wont refresh the iframe.
<script type="text/javascript">
var page = 'data/apps/<? echo $_SESSION['name']; ?><? echo $_SESSION['last']; ?>App.html', lM;
function checkModified(){
$.get(page, function(a,a,x){
var mod = x.getResponseHeader('last-modified');
if(lM != mod){
lM = mod;
document.getElementById("frame").src += "";
}
}
}
setInterval(checkModified, 5000); // every 5 seconds
</script>
What I want to achieve is when there are changes on the target page, the iframe will automatically reload itself so that the changes can be shown to the user. Both pages are located in the same domain.
Firstly, you had a missing closing bracket ")" at the end of the $.get method.
The main problem, though, was probably that your server is not sending proper Last-Modified headers. The server I tested on didn't send any, meaning mod is undefined. A workaround is to check for Content-Length instead. It's not ideal because an edited page doesn't necessarily change size, but it seems you're in control of the page so you could ensure you add an extra byte to force a refresh.
Here is your checkModified function updated which should work:
function checkModified() {
$.get(page, function(a, b, x) {
var mod = (x.getResponseHeader('Last-Modified')) ? x.getResponseHeader('Last-Modified') : x.getResponseHeader('Content-Length');
if (lM != mod) {
lM = mod;
console.log('Fetched');
document.getElementById("frame").src += "";
}
});
}

Categories