Dynamic iframe content from js response - javascript

I have a page where I'm dynamically creating an empty iframe. Then I need to populate the iframe content by retrieving some js-script response data. Everything works fine when I call js URL:
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).src=\'' + src + '\'">';
doc.open().write(html);
doc.close();
})(document);
But I need to run the widget.js with some dynamic parameter. Is there a way to pass the uri variable value to the script? I use pure JavaScript not jQuery

Here's a quick modification of your code to show how its possible.
Your doc variable is the document element of the iFrame. Setting a variable on it will allow you to access it from code running within the iFrame.
https://jsfiddle.net/78gf5e8q/
(function(d) {
var iframe = d.body.appendChild(d.createElement('iframe')),
doc = iframe.contentWindow.document,
options = {
objid: 152,
key: 316541321
},
//src = "host/widget.js",
uri = encodeURIComponent(JSON.stringify(options));
doc.someVar = "Hello World!";
iframe.id = "iframewidget";
iframe.width = 200;
iframe.height = 300;
var html = '<body onload="var d=document;' +
'd.getElementsByTagName(\'head\')[0].appendChild(d.createElement(\'script\')).innerHTML=\'alert(document.someVar)\'">';
doc.open().write(html);
doc.close();
})(document);
Edit: you were also passing in a non existent var called js into doc.open().write(js); I changed it to .write(html);
Edit 2: For cross domain you'll probably get "Permission Denied" on that var.

Related

How to write data in JSON file in the EJS template file [duplicate]

I want to Write Data to existing file using JavaScript.
I don't want to print it on console.
I want to Actually Write data to abc.txt.
I read many answered question but every where they are printing on console.
at some place they have given code but its not working.
So please can any one help me How to actually write data to File.
I referred the code but its not working:
its giving error:
Uncaught TypeError: Illegal constructor
on chrome and
SecurityError: The operation is insecure.
on Mozilla
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
So can we actually write data to file using only Javascript or NOT?
You can create files in browser using Blob and URL.createObjectURL. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
Some suggestions for this -
If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
To store some information on the client side that is considerably small, you can go for cookies.
Using the HTML5 API for Local Storage.
If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.
But if you want to write data, and enable user to download as a file to local. the following code works:
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
}
to use it:
download('the content of the file', 'filename.txt', 'text/plain');
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
If you want to download binary data look here
Update
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
Above answer is useful but, I found code which helps you to download text file directly on button click.
In this code you can also change filename as you wish. It's pure javascript function with HTML5.
Works for me!
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file
In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {
function download() {
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {
download()
}, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>
Use the code by the user #useless-code above (https://stackoverflow.com/a/21016088/327386) to generate the file.
If you want to download the file automatically, pass the textFile that was just generated to this function:
var downloadFile = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
I found good answers here, but also found a simpler way.
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)
You can style the link as a button using bootstrap, which is still pure javascript, except for styling.
Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.
This example needs only one button click to create the text-blob and download it:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
Here is a single-page local-file version for use when you need the extra processing functionality of a scripting language.
Save the code below to a text file
Change the file extension from '.txt' to '.html'
Right-click > Open With... > notepad
Program word processing as needed, then save
Double-click html file to open in default browser
Result will be previewed in the black box, click download to get the resulting text file
Code:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
// do text manipulation here
let string1 = 'test\r\n';
let string2 = 'export.';
// assemble final string
const finalText = string1 + string2;
// convert to blob
const data = new Blob([finalText], {type: 'text/plain'});
// create file link
const link = document.createElement('a');
link.innerHTML = 'download';
link.setAttribute('download', 'data.txt');
link.href = window.URL.createObjectURL(data);
document.body.appendChild(link);
// preview the output in a paragraph
const htmlBreak = string => {
return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
const preview = document.createElement('p');
preview.innerHTML = htmlBreak(finalText);
preview.style.border = "1px solid black";
document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>

Internally referenced javascript is not loading when content is loaded via ajax

I am updating a div content via ajax call. The response(html) which i get contains a reference to an internal JavaScript file.
The referenced javascript is not getting loaded. How can I solved the issue.
Below is how I am setting it to a div.
document.getElementById('content-wrapper').innerHTML = data;
The file is loaded correctly when i set the content using jQuery's .html() function. But for that we have to disable 'unsafe-eval' in our content security policy. So jQuery is not an option.
#mplungjan answers did help but i am getting below eror
Try this
const wrapper = document.getElementById('content-wrapper')
wrapper.innerHTML = data;
const scr = wrapper.querySelector("script");
const newScr = document.createElement("script");
newScr.src = scr.src;
try {
document.head.appendChild(newScr)
} catch (e) {
console.log("nope")
}
const data = `This is a script <script src="https://worldwide.espacenet.com/scripts/powered_by_espacenet.js"><\/script> embedded in a string`
const wrapper = document.getElementById('content-wrapper')
wrapper.innerHTML = data;
const scr = wrapper.querySelector("script");
const newScr = document.createElement("script");
newScr.src = scr.src;
console.log(newScr.src);
// this is to handle the document.write in this particular script
const myWrite = document.write;
document.write = function(str) {
wrapper.innerHTML += str
}
try {
document.head.appendChild(newScr)
} catch (e) {
console.log("nope")
}
<form name=""></form>
<div id="content-wrapper"></div>

Discord Webhook Embeds with JavaScript POST Requests

I tried to create an embed message using a discord webhook and a javascript post method.
Here's the method I use:
function requestWithoutAjax( url, params, method ){
params = params || {};
method = method || 'post';
// function to remove the iframe
var removeIframe = function( iframe ){
iframe.parentElement.removeChild(iframe);
};
// make a iframe...
var iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.onload = function(){
var iframeDoc = this.contentWindow.document;
// Make a invisible form
var form = iframeDoc.createElement('form');
form.method = method;
form.action = url;
iframeDoc.body.appendChild(form);
// pass the parameters
for( var name in params ){
var input = iframeDoc.createElement('input');
input.type = 'hidden';
input.name = name;
input.value = params[name];
form.appendChild(input);
}
form.submit();
// remove the iframe
setTimeout( function(){
removeIframe(iframe);
}, 500);
};
document.body.appendChild(iframe);
}
When I try to call this method with this JSON: {"content":"Some message"} the webhook sends "Some message" into my discord chat.
But when I try to use an embed (https://discordapp.com/developers/docs/resources/webhook#execute-webhook & https://discordapp.com/developers/docs/resources/channel#embed-object), with this JSON: {"embeds":[{"title":"A title","description":"A description","color":3447003}]} it just doesn't send the embed message.
Am I formatting the JSON wrong, or is it something other?
Maybe someone of you can solve my problem.

PhantomJS: Get page content with correct selector

I'm trying to get some content off of a page that renders elements post load like such:
var URL = '/';
var IMG = 'http://img.site.com/';
for(var k=0;k<thumb.length;k++)
{
html = html +
'<div class="thumbnail"><a href="'+URLthumb+tumb_id[k]+'">
<img class="th" src='IMG+thumb[k]' /></a></div>';
}
document.write(html);
I'm currently loading this page with:
var system = require('system');
var page = require('webpage').create();
page.open('http://example.com/search?q=some+query+goes+here', function() {
var title = page.evaluate(function() {
return document.documentElement.outerHTML;
});
system.stdout.writeLine(title);
phantom.exit();
});
document.documentElement.outerHTML returns the page pre-render no matter how long I wait. What is the best object to get the page content post render?
What am I doing wrong?

Inserting Google Adwords Conversion Tracking with Javascript or jQuery

I'm pretty new to javascript, and therein probably lies my problem. I'm trying to track AdWords conversions that occur within a widget on our site. The user fills in a form and the result from the widget is published in the same div without a page refresh. The issue I'm having is when I try to appendChild (or append in jQuery) both script elements in Google's code (shown below) the page gets 302 redirected to a blank Google page (or at least that's what it looks like through FireBug).
I'm able to provide a callback method for the results of the form, and that's where I'm trying to insert the AdWords tracking code. For reference, this is the code provided by Google:
<script type="text/javascript">
/* <![CDATA[ */
var google_conversion_id = 993834405;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "bSpUCOP9iAIQpevy2QM";
/* ]]> */
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&guid=ON&script=0"/>
</div>
</noscript>
Pretty standard stuff. So, what I'm trying to do is insert this into the results page using the callback method (which is provided). Frankly, I'm redirected no matter when I try to insert this code using js or jQuery (either on original page load or in the callback) so maybe the callback bit is irrelevant, but it's why I'm not just pasting it into the page's code.
I've tried a number of different ways to do this, but here's what I currently have (excuse the sloppiness. Just trying to hack my way through this at the moment!):
function matchResultsCallback(data){
var scriptTag = document.createElement('script');
scriptTag.type = "text/javascript";
scriptTag.text = scriptTag.text + "/* <![CDATA[ */\n";
scriptTag.text = scriptTag.text + "var google_conversion_id \= 993834405\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_language \= \"en\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_format \= \"3\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_color \= \"ffffff\"\;\n";
scriptTag.text = scriptTag.text + "var google_conversion_label \= \"bSpUCOP9iAIQpevy2QM\"\;\n";
scriptTag.text = scriptTag.text + "/* ]]> */\n";
$('body').append(scriptTag);
$('body').append("<script type\=\"text\/javascript\" src\=\"http://www.googleadservices.com/pagead/conversion.js\" />");
//I have also tried this bit above using the same method as 'scriptTag' with no luck, this is just the most recent iteration.
var scriptTag2 = document.createElement('noscript');
var imgTag = document.createElement('img');
imgTag.height = 1;
imgTag.width = 1;
imgTag.border = 0;
imgTag.src = "http://www.googleadservices.com/pagead/conversion/993834405/?label=bSpUCOP9iAIQpevy2QM&guid=ON&script=0";
$('body').append(scriptTag2);
$('noscript').append(imgTag);
}
The really odd thing is that when I only insert one of the script tags (it doesn't matter which one), it doesn't redirect. It only redirects when I try to insert both of them.
I've also tried putting the first script tag into the original page code (as it's not making any calls anywhere, it's just setting variables) and just inserting the conversions.js file and it still does the redirect.
If it's relevant I'm using Firefox 3.6.13, and have tried the included code with both jQuery 1.3 and 1.5 (after realizing we were using v1.3).
I know I'm missing something! Any suggestions?
Nowadays it is convenient to use the Asynchronous Tag at http://www.googleadservices.com/pagead/conversion_async.js that exposes the window.google_trackConversion function.
This function can be used at any time. For example after submitting a form, like in your case.
See https://developers.google.com/adwords-remarketing-tag/asynchronous/
Update 2018
Situation changed and it seems that you have more options now with the gtag.js: https://developers.google.com/adwords-remarketing-tag/
If you're using jQuery in your pages, why don't you use the getScript method of the same to poll the conversion tracking script after setting the required variables?
This is what I usually do, once I've received a success response from my AJAX calls.
var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
google_conversion_value = <Your value here if any>;
}
$jQ.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
This works just fine for me. If you want a more detailed example:
$.ajax({
async: true,
type: "POST",
dataType: "json",
url: <Your URL>,
data: _data,
success: function( json ) {
// Do something
// ...
// Track conversion
var google_conversion_id = <Your ID Here>;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "<Your Label here>";
var google_conversion_value = 0;
if (100) {
google_conversion_value = <Your value here if any>;
}
$.getScript( "http://www.googleadservices.com/pagead/conversion.js" );
} // success
});
If you use other libraries such as Mootools or Prototype, I'm sure they have similar in-built methods. This AFAIK is one of the cleanest approaches.
this simple code worked for me (the $.getScript version didn't).
var image = new Image(1,1);
image.src = 'http://www.googleadservices.com/pagead/conversion/' + id + '/?label=' + label + ' &guid=ON&script=0';
// This takes care of it for jQuery. Code can be easily adapted for other javascript libraries:
function googleTrackingPixel() {
// set google variables as globals
window.google_conversion_id = 1117861175
window.google_conversion_language = "en"
window.google_conversion_format = "3"
window.google_conversion_color = "ffffff"
window.google_conversion_label = "Ll49CJnRpgUQ9-at5QM"
window.google_conversion_value = 0
var oldDocWrite = document.write // save old doc write
document.write = function(node){ // change doc write to be friendlier, temporary
$("body").append(node)
}
$.getScript("http://www.googleadservices.com/pagead/conversion.js", function() {
setTimeout(function() { // let the above script run, then replace doc.write
document.write = oldDocWrite
}, 100)
})
}
// and you would call it in your script on the event like so:
$("button").click( function() {
googleTrackingPixel()
})
In your Adwords account - if you change the conversion tracking event to "Click" instead of "Page Load" it will provide you with code that creates a function. It creates a snippet like this:
<!-- Google Code for Developer Contact Form Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = <Your ID Here>;
w.google_conversion_label = "<Your value here if any>";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
window.google_is_call = true;
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>
Then in your code you just call:
goog_report_conversion();
Or for a link or image click:
click here
After trying everything the link Funka provided (http://articles.adamwrobel.com/2010/12/23/trigger-adwords-conversion-on-javascript-event) was what worked for me. Like he said it's scary to overwrite document.write, but
It seems like this is what you have to do unless you can load the script before the page load.
Since the script uses document.write so it needs to be re-written
document.write = function(node){ // exactly what document.write should of been doing..
$("body").append(node);
}
window.google_tag_params = {
prodid: pageId,
pagetype: pageTypes[pageType] || "",
value: "234324342"
};
window.google_conversion_id = 2324849237;
window.google_conversion_label = "u38234j32423j432kj4";
window.google_custom_params = window.google_tag_params;
window.google_remarketing_only = true;
$.getScript("http://www.googleadservices.com/pagead/conversion.js")
.done(function() {
// script is loaded.
});
See https://gist.github.com/c7a316972128250d278c
As you have seen, the google conversion tag only calls on a redraw. I had to make sure it was called when a part of a page was redrawn. (Due to some bad website design that I could not fix at the moment.) So I wrote a function to call from an onClick event.
Essentially, all you have to do is to call doConversion();
Here is what we ended up with:
// gothelp from from http://www.ewanheming.com/2012/01/web-analytics/website-tracking/adwords-page-event-conversion-tracking
var Goal = function(id, label, value, url) {
this.id = id;
this.label = label;
this.value = value;
this.url = url;
};
function trackAdWordsConversion(goal, callback) {
// Create an image
var img = document.createElement("img");
// An optional callback function to run follow up processed after the conversion has been tracked
if(callback && typeof callback === "function") {
img.onload = callback;
}
// Construct the tracking beacon using the goal parameters
var trackingUrl = "http://www.googleadservices.com/pagead/conversion/"+goal.id;
trackingUrl += "/?random="+new Date().getMilliseconds();
trackingUrl += "&value="+goal.value;
trackingUrl += "&label="+goal.label;
trackingUrl += "&guid=ON&script=0&url="+encodeURI(goal.url);
img.src = trackingUrl;
// Add the image to the page
document.body.appendChild(img);
// Don't display the image
img.style = "display: none;";
}
function linkClick(link, goal) {
try {
// A function to redirect the user after the conversion event has been sent
var linkClickCallback = function() {
window.location = link.href;
};
// Track the conversion
trackAdWordsConversion(goal, linkClickCallback);
// Don't keep the user waiting too long in case there are problems
setTimeout(linkClickCallback, 1000);
// Stop the default link click
return false;
} catch(err) {
// Ensure the user is still redirected if there's an unexpected error in the code
return true;
}
}
function doConversion() {
var g = new Goal(YOUR CODE,YOUR_COOKIE,0.0,location.href);
return linkClick(this,g);
}
I tried all the ways to manually include conversion.js, it all loaded the script, but didn't further execute what we needed inside the script, there's a simple solution.
Just put your conversion code in a separate HTML, and load it in an iframe.
I found code to do that at http://www.benjaminkim.com/ that seemed to work well.
function ppcconversion() {
var iframe = document.createElement('iframe');
iframe.style.width = '0px';
iframe.style.height = '0px';
document.body.appendChild(iframe);
iframe.src = '/track.html'; // put URL to tracking code here.
};
then just call ppcconversion() wherever in the JS you like to record it.
All I do is return the code (or in our case, an image) along with the "success" message in the callback.
When a contact form is submitted, or a registration form filled out and submitted, we post to a php script using jQuery, then output a "thank-you" message to a div:
"$first_name, Thanks for requesting more information. A representative will contact you shortly."
... followed by the 1x1 gif Google provides.
Here's the jQuery:
$.post('script.php',{'first_name':first_name,'last_name':last_name,'email':email,'phone1':phone1,'password':password,},function(data){
var result=data.split("|");
if(result[0] ==='success'){
$('#return').html(result[1] + $result[2]);
And the php...
echo 'success|'.$first_name.', Thanks for requesting more information.
A representative will contact you shortly.|<img height="1" width="1" alt="" src="http://www.googleadservices.com/pagead/conversion/xxxxxxxx/imp.gif?value=0&label=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&script=0"/>';
You might need to throw in a "document.location.reload();" if it isn't being picked up by google
For anyone still looking for a good solution to this, Google supports AJAX Conversions natively now through their Google Analytics API.
You can do it by making a event API call in Google Analytics. What you do is setup an Analytics event, tie it to a goal, then import that goal into AdWords as a conversion. It's a bit of a lengthy process but it's a clean solution.
Check out This Page for a tutorial
This works for me:
window.google_trackConversion({
google_conversion_id: 000000000,
conversion_label : "xxxxxxxxxxxx",
google_remarketing_only: false,
onload_callback : function(){
//do something :)
}
});

Categories

Resources