Random behaviour of SWF loading - javascript

I have a really strange behiavour with the loading of a SWF file: the buttons on it are working on the first load, but if I reload the page they don't work anymore, even if I empty my cache or force SWF reload by appending a random parameter at the end of the URL. The buttons are generated from a XML file called in the init function.
Here is how I call my swf :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script
<script type="text/javascript">
// <![CDATA[
window.onload=function(){
var _time = (new Date()).getTime();
var params = {wmode: "transparent", src: "http://www.mywebsite.com/sites/default/files/medias/map/monde.swf?" + _time};
var flashvars = {site: "/fr"};
swfobject.embedSWF("http://www.mywebsite.com/sites/default/files/medias/map/monde.swf?" + _time, "flashContent", 920, 450, "10", false, flashvars, params);
};
// ]]>
</script>
<div id="flashContent"> </div>
The only way to get the buttons back is to edit the source in Firebug, change the SWF URL with something random and change it back so the URL is loaded again (it's not working on the first try, I have to do it few times before it works).
I don't have any cache on the SWF and on the XML I'm calling from AS3, so I don't understand how I can have such a random behaviour :
Here is the relevant parts of the AS3 script :
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var site:String = "";
if (this.loaderInfo.parameters.site != undefined)
site = this.loaderInfo.parameters.site;
_uLoader = new URLLoader();
_uLoader.addEventListener(Event.COMPLETE, _initMap);
var httpHeader : URLRequestHeader = new URLRequestHeader("pragma", "no-cache");
var httpRequest : URLRequest = new URLRequest(site+"/ajax/mywebsite_tools/list_master");
httpRequest.requestHeaders.push(httpHeader);
httpRequest.method = URLRequestMethod.GET;
httpRequest.data = new URLVariables("time="+Number(new Date().getTime()));
_uLoader.load(httpRequest);
_supportContinent = new MovieClip();
this.addChild(_supportContinent);
}
private function _initMap(e:Event):void
{
var cs:mywebsiteSingleton = mywebsiteSingleton.getInstance();
var xml:XML = new XML(_uLoader.data);
cs.xml = xml;
btRetour.buttonMode = true;
btRetour.mouseChildren = false;
btRetour.txt.text = xml.retour.text();
btRetour.gotoAndStop('OUT');
addEventListener(mywebsiteEvent.CONTINENT_CLICK, _contientClick);
btRetour.addEventListener(MouseEvent.CLICK, _retourMonde);
btRetour.addEventListener(MouseEvent.ROLL_OVER, _over);
btRetour.addEventListener(MouseEvent.ROLL_OUT, _out);
}

Figured it out. It was rather trivial in fact, the _initMap() function was randomly called before or after my buttons appear on the timeline. So if i get the xml too fast, the _initMap() function try to refer to a button that doesn't exist.
Fixed it with something a bit dirty, but anyway it works :
private function _initMap(e:Event):void
{
if(!btRetour || btRetour == null || !btRetour.hasOwnProperty("buttonMode")) {
setTimeout(_initMap, 500, e);
return;
}
// ...
}

Related

Returned JavaScript value wont render inside a div element

This a basic question (Posting this again, as it was not re-opened after I updated the question). But I couldn't find any duplicates on SO.
This is a script I intend to use in my project on different pages. The purpose is to override the default ID shown in a span element to the order number from the URL parameter session_order. This doesn't affect anything and only enhances the UX for my project.
scripts.js (loaded in the header):
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
And in my HTML template, I call the function this way,
<div onload="this.innerHTML = get_url_parameter(window.location.href, 'session_order');">24</div>
Also tried this,
<div><script type="text/javascript">document.write(get_url_parameter(window.location.href, 'session_order'));</script></div>
When the page is rendered, nothing changes. No errors or warnings in the console either for the first case.
For the second case, console logged an error Uncaught ReferenceError: get_url_parameter is not defined, although script.js loads before the div element (without any errors).
Normally, I'd do this on the server-side with Flask, but I am trying out JavaScript (I am new to JavaScript) as it's merely a UX enhancement.
What am I missing?
Try this:
// This is commented because it can't be tested inside the stackoverflow editor
//const url = window.location.href;
const url = 'https://example.com?session_order=13';
function get_url_parameter(url, parameter) {
const u = new URL(url);
return u.searchParams.get(parameter);
}
window.onload = function() {
const el = document.getElementById('sessionOrder');
const val = get_url_parameter(url, 'session_order');
if (val) {
el.innerHTML = val;
}
}
<span id="sessionOrder">24</span>
Define the function you need for getting the URL param and then on the window load event, get the URL parameter and update the element.
Here you go. Try to stay away from inline scripts using document.write.
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
window.addEventListener('load', function() {
const url = 'https://yourpagesdomain.name/?session_order=hello'; //window.location.href;
const sessionOrder = get_url_parameter(url, 'session_order');
document.getElementById('sessionOrder').innerText = sessionOrder;
});
<div id="sessionOrder"></div>
The order of your markup and script matters...
<div></div>
<script>
function get_url_parameter(url, parameter) {
var url = new URL(url);
return url.searchParams.get(parameter);
}
</script>
<script>
document.querySelector('div').innerHTML = get_url_parameter('https://example.com?session_order=2', 'session_order');
</script>

On Click preload images using javascript

Directly calling preload function works without any issues. But when preload() is called onClick,even after loading of images ,not ending its processing and that can be viewed as "loading..." in a browser
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
document.write('<img src="' + imageArray[i] + '" width="335px" height="180px" alt="[Alternative text]" />');
imageObj.src=imageArray[i];
}
}
}
Gallery
You can't call document.write after the page is loaded. If you want to add something to the page, you must call DOM manipulation functions like document.createElement (see example).
But what you do in your function doesn't look like preloading but rather like direct insertion of images in the page.
If you want to preload images, that is to ask the browser to cache them so that they are instantly available later, then you'd better use XmlHttpRequest instead of creating Image elements. Issuing XmlHttpRequest requests doesn't make the browser display a hourglass and the user doesn't feel like something is happening.
I made a small "library" last week-end just for this : easily preload resources.
var preload = (function(){
var queue = [], nbActives = 0;
function bip(){
if (queue.length==0 || nbActives>=4) return;
nbActives++;
var req = new XMLHttpRequest(), task=queue.shift();
req.open("GET", task.src, true);
req.onload = function () {
nbActives--;
bip();
if (task.callback) task.callback(task.src);
};
req.send();
}
return function(src, priority, callback) {
queue[priority?'unshift':'push']({src:src, callback:callback});
bip();
}
})();
Usage :
preload('path/to/file.png'); // preload the file
preload('path/to/file.png', true); // preload the file with high priority
preload('path/to/file.png', false, callback); // preload the file and be notified when it's finished
Github repository : https://github.com/Canop/preload

Visual Studio, Windows 8 HTML5 Javascript Questions

Was not sure what to title this post, I've been having a go at trying to make a little Windows 8 app, I don't have much knowledge and sorry in advance if this is hard to understand, below is my itemDetail.js
(function () {
"use strict";
WinJS.UI.Pages.define("/pages/itemDetail/itemDetail.html", {
// This function is called whenever a user navigates to this page. It
// populates the page elements with the app's data.
ready: function (element, options) {
var item = options && options.item ? Data.resolveItemReference(options.item) : Data.items.getAt(0);
element.querySelector(".titlearea .pagetitle").textContent = item.group.title;
element.querySelector("article .item-title").textContent = item.title;
element.querySelector("article .item-subtitle").textContent = item.subtitle;
element.querySelector("article .item-image").src = item.backgroundImage;
element.querySelector("article .item-image").alt = item.subtitle;
element.querySelector("article .item-content").innerHTML = item.content;
element.querySelector("article .track1").innerHTML = item.track1;
WinJS.Utilities.query("#playMP3").listen("click", getStartVideoFuntion("http://www.ikkmusic.com/ikkmusic.com%20mix.mp3"));
},
});
function getStartVideoFuntion(src) {
return function () {
// Set video element's source
var vid = WinJS.Utilities.query("#playback")[0];
vid.src = src;
vid.play();
};
}})();
So I have a file called data.js which has all the sample data in, and I'm getting the info here and displaying it and it works fine, but my problem is with the bottom one (below) where the url is shown, when the button is pressed it plays the url in the html5 player tag, this works, is there a way for me to put the contents of item.track1 where the URL is now, I can't get it to put the contents of the data there.
WinJS.Utilities.query("#playMP3").listen("click", getStartVideoFuntion("http://www.ikkmusic.com/ikkmusic.com%20mix.mp3"));
WinJS.Utilities.query("#playMP3").listen("click", getStartVideoFuntion(item.track1));

Chrome Extension doesn't considers optionvalue until reloaded

I'm working on my first Chrome Extension. After learning some interesting notions about jquery i've moved to raw javascript code thanks to "Rob W".
Actually the extension do an XMLHttpRequest to a remote page with some parameters and, after manipulating the result, render an html list into the popup window.
Now everything is up and running so i'm moving to add some option.
The first one was "how many elements you want to load" to set a limit to the element of the list.
I'm using fancy-setting to manage my options and here's the problem.
The extension act like there's a "cache" about the local storage settings.
If i do not set anything and perform a clean installation of the extension, the default number of element is loaded correctly.
If i change the value. I need to reload the extension to see the change.
Only if a remove the setting i see the extension work as intended immediately.
Now, i'm going a little more into specific information.
This is the popup.js script:
chrome.extension.sendRequest({action: 'gpmeGetOptions'}, function(theOptions) {
//Load the limit for topic shown
console.log('NGI-LH -> Received NGI "max_topic_shown" setting ('+theOptions.max_topic_shown+')');
//Initializing the async connection
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://gaming.ngi.it/subscription.php?do=viewsubscription&pp='+theOptions.max_topic_shown+'&folderid=all&sort=lastpost&order=desc');
xhr.onload = function() {
var html = "<ul>";
var doc = xhr.response;
var TDs = doc.querySelectorAll('td[id*="td_threadtitle_"]');
[].forEach.call(TDs, function(td) {
//Removes useless elements from the source
var tag = td.querySelector('img[src="images/misc/tag.png"]'); (tag != null) ? tag.parentNode.removeChild(tag) : false;
var div_small_font = td.querySelector('div[class="smallfont"]'); (small_font != null ) ? small_font.parentNode.removeChild(small_font) : false;
var span_small_font = td.querySelector('span[class="smallfont"]'); (small_font != null ) ? small_font.parentNode.removeChild(small_font) : false;
var span = td.querySelector('span'); (span != null ) ? span.parentNode.removeChild(span) : false;
//Change the look of some elements
var firstnew = td.querySelector('img[src="images/buttons/firstnew.gif"]'); (firstnew != null ) ? firstnew.src = "/img/icons/comment.gif" : false;
var boldtext = td.querySelector('a[style="font-weight:bold"]'); (boldtext != null ) ? boldtext.style.fontWeight = "normal" : false;
//Modify the lenght of the strings
var lenght_str = td.querySelector('a[id^="thread_title_"]');
if (lenght_str.textContent.length > 40) {
lenght_str.textContent = lenght_str.textContent.substring(0, 40);
lenght_str.innerHTML += "<span style='font-size: 6pt'> [...]</span>";
}
//Removes "Poll:" and Tabulation from the strings
td.querySelector('div').innerHTML = td.querySelector('div').innerHTML.replace(/(Poll)+(:)/g, '');
//Modify the URL from relative to absolute and add the target="_newtab" for the ICON
(td.querySelector('a[id^="thread_title"]') != null) ? td.querySelector('a[id^="thread_title"]').href += "&goto=newpost" : false;
(td.querySelector('a[id^="thread_goto"]') != null) ? td.querySelector('a[id^="thread_goto"]').href += "&goto=newpost": false;
(td.querySelector('a[id^="thread_title"]') != null) ? td.querySelector('a[id^="thread_title"]').target = "_newtab": false;
(td.querySelector('a[id^="thread_goto"]') != null) ? td.querySelector('a[id^="thread_goto"]').target = "_newtab": false;
//Store the td into the main 'html' variable
html += "<li>"+td.innerHTML+"</li>";
// console.log(td);
});
html += "</ul>";
//Send the html variable to the popup window
document.getElementById("content").innerHTML = html.toString();
};
xhr.responseType = 'document'; // Chrome 18+
xhr.send();
});
Following the background.js (the html just load /fancy-settings/source/lib/store.js and this script as Fancy-Setting How-To explains)
//Initialization fancy-settings
var settings = new Store("settings", {
"old_logo": false,
"max_topic_shown": "10"
});
//Load settings
var settings = settings.toObject();
//Listener who send back the settings
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
if (request.action == 'gpmeGetOptions') {
sendResponse(settings);
}
});
The console.log show the value as it has been cached, as i said.
If i set the value to "20", It remain default until i reload the extension.
If i change it to 30, it remain at 20 until i reload the extension.
If something more is needed, just ask. I'll edit the question.
The problem appears to be a conceptual misunderstanding. The background.js script in a Chrome Extension is loaded once and continues to run until either the extension or the Chrome Browser is restarted.
This means in your current code the settings variable value is loaded only when the extension first starts. In order to access values that have been updated since the extension is loaded the settings variable value in background.js must be reloaded.
There are a number of ways to accomplish this. The simplest is to move the settings related code into the chrome.extension.onRequest.addListener callback function in background.js. This is also the most inefficient solution, as settings are reloaded every request whether they have actually been updated or not.
A better solution would be to reload the settings value in background.js only when the values are updated in the options page. This uses the persistence, or caching, of the settings variable to your advantage. You'll have to check the documentation for implementation details, but the idea would be to send a message from the options page to the background.js page, telling it to update settings after the new settings have been stored.
As an unrelated aside, the var keyword in the line var settings = settings.toObject(); is not needed. There is no need to redeclare the variable, it is already declared above.

I am try to make this code work in Visual Studio 2010 and it says my "SWFObject is undefined" in the firefox brower. And the swfobject.js is a 2.2

I am trying to make this code work in Visual Studio 2010 and it says my "SWFObject is undefined" in the firefox brower. And the swfobject.js is a v2.2 .I want the .swf in the "gs" div to play first and then play the other .swf in the "billboard" div, when the "gs" .swf is finish playing or clicked off. So that the .swfs don't play at the same time and are slow.
<script type="text/javascript" src="/Scripts/swfobject.js"></script>
<script language="javascript" type="text/javascript" src="/Scripts/jquery-1.2.6.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
if(readCookie("flashPlayed") == "true"){
showWater();
}
});
function launchFlash(){
if(readCookie("flashPlayed") != "true"){
var homeflash = new SWFObject("/Content/swf/2BigGS.swf", "BG", "1003", "840", "8");
homeflash.addParam("wmode","transparent");
homeflash.write("gs");
setTimeout("showWater()", 33000);
setTimeout("removeFlash()", 33000);
}
}
function readCookie(cookieName){
var searchName = cookieName + "="
var cookies = document.cookie
var start = cookies.indexOf(cookieName)
if (start == -1){ // cookie not found
return ""
}
start += searchName.length //start of the cookie data
var end = cookies.indexOf(";", start)
if (end == -1){
end = cookies.length
}
return cookies.substring(start, end)
}
function showwater(){
$("#billboard").fadeIn("slow");
document.cookie="flashPlayed=true"
}
function removeFlash(){
$("#gs").empty();
$("#gs").animate( { top:"-9999px"}, 1 )
}
</script>
SWFObject 2 has an entirely different API from 1.5 - it doesn't define anything named "SWFObject" - and also doesn't use a constructor function.
One way of using it:
var flashvars = null;
var params = { "wmode": "transparent" };
var attributes = null;
swfobject.embedSWF(
"/Content/swf/2BigGS.swf", "BG", "1003", "840", "8", false,
flashvars, params, attributes);
Also be aware that version 2 replaces the element you specify for swf insertion, i.e.:
In version 1.5:
<div id="gs"></div>
became:
<div id="gs"><object id="BG">...</object></div>
In version 2.0:
<div id="gs"><div id="BG"></div></div>
becomes:
<div id="gs"><object id="BG">...</object></div>
I.e., a "BG" element must already be there - it's replaced, rather than inserted.
This may mean that you need to change other parts of the code. For example, you can't check if the swf has been inserted by checking for an element with the id "BG", because BG is still there (as a <div> in the above example) even if inserting the swf failed.
http://code.google.com/p/swfobject/wiki/documentation

Categories

Resources