I need to detect whether a page contains flash objects ,I do not mean browser flash support. Have you sorted out something similar?
2 Answers
A shorter version of giannis christofakis' answer for modern browsers (should work in IE9+):
function containsSWFObjects() {
var s,
selectors = [
'object param[name="movie"][value*=".swf"]',
'object param[name="src"][value*=".swf"]',
'embed[src*=".swf"]',
'object[data*=".swf"]'
];
while (s = selectors.pop()) {
if (document.querySelectorAll(s).length) {
return true;
}
}
return false;
}
You can use jQuery instead of document.querySelectorAll which might be slightly slower, but will probably work with every browser.
Comments
My approach is to distinguish flash objects from others such as pictures and videos by their file extension. It's the only thing that it cannot be omitted. You can spot some cases below.
function getFileExtension(filename) {
//Since you only looking for swf.
return filename.substr(filename.length - 3).toUpperCase();
//return filename.split('.').pop().toUpperCase();
}
function isSwfFile(filename) {
if ( getFileExtension(filename) == "SWF") {
return true;
}
return false;
}
function containsSWFObjects() {
//Try to get all OBJECT tags
var objects = document.getElementsByTagName('object');
var i ,j ;
for (i=0; i < objects.length; i++) {
//Check for <object width="400" height="400" data="helloworld.swf"></object>
var data = objects[i].getAttribute("data");
if (data) {
if (isSwfFile(data)) {
console.log(data);
return true;
}
}
//Check for <param name="movie" value="file.swf"/>
//and <param name="SRC" value="bookmark.swf">
var param = objects[i].getElementsByTagName('param');
for (j=0; j < param.lenght; j++) {
var name = param[j].getAttribute("name").toUpperCase();
if (name) {
if ( name == "MOVIE" || name == "SRC") {
if ( isSwfFile( param[j].getAttribute("value") ) ) {
console.log(param[j].getAttribute("value"));
return true;
}
}
}
}
}
//Check for EMBED tag
var embed = document.getElementsByTagName('embed');
for (i=0; i < len; i++) {
//Check for <embed src="file.swf">
var src = embed[i].getAttribute('src');
if (src) {
if (isSwfFile(src)) {
console.log(src);
return true;
}
}
}
return false;
}
if ( containsSWFObjects() ) {
console.log("Contain SWFs");
} else {
console.log("Doesn't contain SWFs");
}
OBJECTtag.