Javascript remote src not working - javascript

If I put JavaScript inline in my page it works fine; however, if I put the script on a remote server so I can clean things up, it quits working.
Go to:
http://www.salescart.com/cloud/store/test2.html
Here is the JavaScript is inline
{you can see the iframe sizes correctly without issue at this url}
Go to:
http://www.salescart.com/cloud/store/test.html
This is the same exact html file except that the operative javascript is put into a remote src.
This is the JavaScript in the remote src:
<script type="text/javascript">
//MDN PolyFil for IE8 (This is not needed if you use the jQuery version)
if (!Array.prototype.forEach){
Array.prototype.forEach = function(fun /*, thisArg */){
"use strict";
if (this === void 0 || this === null || typeof fun !== "function")
throw new TypeError();
var t = Object(this),
len = t.length >>> 0,
thisArg = arguments.length >= 2 ? arguments[1] : void 0;
for (var i = 0; i < len; i++)
if (i in t)
fun.call(thisArg, t[i], i, t);
};
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.salescart.net/checkout20/src/iframeResizer.min.js"></script>
<script type="text/javascript">
iFrameResize({
log : true, // Enable console logging
enablePublicMethods : true, // Enable methods within iframe hosted page
checkOrigin : false // Disable CheckOrigin
});
</script>
{you can see the iframe stops resizing}
I don't understand exactly why this is the case. I appreciate in advance your help. Thanks.

in the js file you wrote
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js";
src="http://www.salescart.net/checkout20/src/iframeResizer.min.js";
which wont work. You need to load those js files in the tests.html itself. Preferablly in the the head tag as
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.salescart.net/checkout20/src/iframeResizer.min.js"></script>

Related

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.

jquery.rotate error

I have an image that I am trying to rotate 30 degrees and move horizontally across a page. However, I don't think I am handling the jquery right because I am getting several errors in the Firefox Web Console. Here are the errors:
[10:30:27.260] ReferenceError: jQuery is not defined # file:///home/ladmin/Desktop/javascriptAnimations/jquery.rotate.1-1.js:1
[10:30:27.274] The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must to be declared in the document or in the transfer protocol. # file:///home/ladmin/Desktop/javascriptAnimations/si110cockroach.html
[10:31:03.416] ReferenceError: $ is not defined # file:///home/ladmin/Desktop/javascriptAnimations/si110cockroach.html:12
I included the script tags with the jquery source at the top like this:
<script language="javascript" type="text/javascript" src="jquery.rotate.1-1.js"></script>
And here is the code where I call the jquery:
function moveLeft(object,x,y){
$(object).rotateRight(30);
object.style.right = x + "px";
object.style.top = y + "px";
if (x < 0 || x > 1500 || y < 0 || y > 1500)
{
object.style.visibility="hidden";
}
else
{
var t = setTimeout(function() { moveLeft(object,x+3,y+0); }, 5);
}
}
Am I not including the source file right or am I not calling the jquery right?
You have to include jquery.min.js before the jquery.rotate.1-1.js script:
<script language="javascript" type="text/javascript" src="jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="jquery.rotate.1-1.js"></script>

Serve alternate external Javascript file depending on if elements are defined or not in the page

Ok, here goes my first question on here.
Setup: We use a javascript based tool to A/B test our landing page designs. I need version A (control) to link to one external javascript file, and version B (variation) to link to an alternate javascript file.
Goal: to have an internal js script at the bottom of the control that looks to see if the tool is in fact serving A or B, and if true, which one was served. The result indicates which external script should be linked.
Issue: regardless of if the tool is in fact serving A or B, the original script is linked first, then if the tool is detected, the appropriate script is linked after that.
Here is my code (I apologize in advance for any newbie mistakes):
//script at bottom of original or tool-served control html page template
<script type="text/javascript">
valForTool = function () {
var variationId = _tool_exp[_tool_exp_ids[0]].combination_chosen;
if (variationId == 1) {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'js/scripts.js';
document.body.appendChild(newScript);
};
}
originalValidation = function () {
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'js/scripts.js';
document.body.appendChild(newScript);
}
$(function(){
if (typeof _tool_exp_ids !== 'undefined' && typeof _tool_exp_ids[0] !== 'undefined') {
valForTool();
} else {
originalValidation();
};
});
</script>
//end script on control or original template
//script on tool-served variation html template - will run after the above script
<script type="text/javascript">
$(function() {
$('#project_info input[type=submit]').removeAttr('disabled');
$('#project_info').unbind();
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'js/scripts2.js';
document.body.appendChild(newScript);
$('.input_text').parent().addClass('contact_field');
});
</script>
// end script on variation template
Any ideas as to what I'm doing wrong? Did I provide enough information? Thanks! I love this site as a reference for my questions, but this is my first time actually posting one.
Shortening it down a bit, it seems like your just doing this:
<script type="text/javascript">
$(function(){
if (typeof _tool_exp_ids !== 'undefined' && typeof _tool_exp_ids[0] !== 'undefined') {
var variationId = _tool_exp[_tool_exp_ids[0]].combination_chosen;
if (variationId == 1) {
$.getScript('js/scripts.js', function() {runSecond();});
}
}else{
$.getScript('js/scripts.js', function() {runSecond();});
}
function runSecond() {
$('#project_info input[type=submit]').removeAttr('disabled').unbind();
$.getScript('js/scripts2.js');
$('.input_text').parent().addClass('contact_field');
}
});
</script>
Now looking at that, it's obvious that both scripts are running no matter what conditions are met in those if/else statements, and I don't really get what it is your trying to do, but the first thing i would do, is to add some console.logs to see if those if/else statements are working like they are supposed to, and then figure what scripts should be loaded under which conditions etc ?

IE throws 'Unspecified error' when reloading a page with swfobject embedded on it

I have a simple page with an swfobject embedded on it.
Looks like IE has problems with the 'filters' property on the embedded object.
My test page looks like that:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<script type="text/javascript" src="../scripts/swfobject.js"></script>
<script type="text/javascript" src="../scripts/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
var url = "";
$(function()
{
var flashvars = {};
var parameters = {};
var attributes = {};
flashvars["data-file"] = url;
parameters.wmode = "transparent";
swfobject.embedSWF("test.swf", "graph1", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, parameters, attributes);
});
</script>
<style type="text/css">
#graph1
{
margin:30px;
height: 400px;
width: 600px;
}
</style>
</head>
<body>
<div id="graph1"></div>
</body>
</html>
note: the test.swf file is the one swfobject package from the download page.
now when i reload the page, it throws an 'Unspecified error' on IE, but not on firefox in which the filters property is set to undefined.
the code that seems to cause the error is in swfobject.js v2.2 (lines 494-504):
/*! SWFObject v2.2 <http://code.google.com/p/swfobject/>
is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
function removeObjectInIE(id) {
var obj = getElementById(id);
if (obj) {
for (var i in obj) {
if (typeof obj[i] == "function") {
obj[i] = null; // when (i == 'filters') we get the error
}
}
obj.parentNode.removeChild(obj);
}
}
Does anyone have any idea why this might be happening?
Two things that immediately caught my eye:
First:
You wrapped your anonymous function (containing the SWFObject code) in a jQuery 'dollar' declaration. The jQuery dollar function "accepts a string containing a CSS selector which is then used to match a set of elements."
Your function doesn't return anything, so it will cause a JavaScript error when jQuery tries to use a null reference as a CSS selector. swfobject.embedSWF does not return a value, either, so it would probably be best to drop the jQuery dollar function from your code.
If you just wanted your code to run in an anonymous function, drop the $ and add a function invocation at the end:
(function()
{
var flashvars = {};
var parameters = {};
var attributes = {};
flashvars["data-file"] = url;
parameters.wmode = "transparent";
swfobject.embedSWF("test.swf", "graph1", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, parameters, attributes);
})();
Second:
You're passing a FlashVars variable name that contains a hyphen, which is illegal in both JavaScript and ActionScript.
Lastly, removeObjectInIE (a subfunction of swfobject.removeSWF) has been thoroughly tested in IE 6, 7, and 8. Since IE9 is still in beta, swfobject doesn't officially support it yet. However, we don't anticipate any issues. I suggest trying the edits I mention above and see if it clears up your issue.
I don't have an idea, why this happens, but you could try to fix it with a try/catch
try{obj[i] = null;}catch(e){}
This should avoid error messages.

getElementsByTagName() behaves differently in IE and FF

I am new to JavaScript, trying to figure out a tag information value. GWT Code is as follows..
public static native boolean isToolBarInstalled() /*-{
alert("Validating the toolbar installed.");
var metas = document.getElementsByTagName('head')[0].getElementsByTagName('meta');
var i;
alert ("Meta length: "+metas.length);
for (i = 0; i < metas.length; i++){
alert("Value: "+metas[i].value);
if (metas[i].getAttribute('name') == "toolbar"){
return true;
}
}
return false;
}-*/;
FF return true whereas IE returns false, for the same page? Any clue/suggestions would be helpful.
WM.
HTML is too huge to post, here is a snippet of the code..
<html>
<head>
....
<title>My App</title>
<meta name="toolbar" content="1.0">
</head>
<body>
.....
</body>
<html>
Works for me in IE7.
Check you haven't got any text content before the <meta> end-tag other than simple whitespace.
If you have any non-whitespace text in or before <html> or <head>, the browser will decide that you meant to open the <body> to contain the text. (This is actually valid in non-XHTML HTML, as the </head> end-tag and the <body> start-tag are optional.) That means closing the <head> section, so the number of <meta> tags inside <head> will be 0.
In any case you might as well say just:
var metas= document.getElementsByTagName('meta');
as the bit about checking they're in <head> is redundant for a valid document; that's the only place <meta> is allowed to appear.
alert("Value: "+metas[i].value);
There's no .value on <meta>, do you mean .content?
if (metas[i].getAttribute('name') == "toolbar"){
Use metas[i].name. There's no reason to use getAttribute/setAttribute on an HTML document and there are problems with it on IE.
Try this:
element.attributes[value].nodeAttribute;
As explained here:
The getAttribute() method will return
"null" in Internet Explorer when
trying to get the for attribute of a
label element.
Might be the same issue...
Well look:
Example
Source
In this example it is working on IE.
function isToolBarInstalled() {
alert("Validating the toolbar installed.");
var metas = document.getElementsByTagName('head')[0].getElementsByTagName('meta');
var i;
alert ("Meta length: "+metas.length);
for (i = 0; i < metas.length; i++){
alert("Value: "+metas[i].value);
var attr = metas[i].getAttribute('name');
// IE workaround
if (attr == null)
{
attr = metas[i].attributes["name"];
if (attr != null) attr = attr.nodeValue;
}
if (attr == "toolbar")
return true;
}
return false;
}
alert( "Is installed: " + isToolBarInstalled() );

Categories