Javascript <-> Flash мост
Эта статья описывает, как вызывать из Javascript методы Flash и наоборот.
Используя эти способы, javascript может получить доступ к буферу обмена ОС, хранимым объектам SharedObject, управлять flash-интерфейсами и многое другое.
Какой бы способ коммуникации мы не выбрали, для начала JS должен уметь находить объект Flash на странице.
Для того, чтобы все работало кроссбраузерно, Flash-ролик нужно вставить с использованием обоих тегов: object и embed , например так:
<object
id="BridgeMovie" width="400" height="200"
classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab">
<param name="movie" value="bridge.swf" />
<param name="allowScriptAccess" value="sameDomain" />
<embed
src="bridge.swf"
name="BridgeMovie" align="middle"
play="true" loop="false" quality="high" allowScriptAccess="sameDomain"
width="400" height="200" scale="exactfit"
type="application/x-shockwave-flash"
pluginspage="http://www.macromedia.com/go/getflashplayer">
</embed>
</object>
В этом примере существенны детали:
- Имя ролика
BridgeMovie дублируется как object.id и embed.name .
- Путь к ролику
bridge.swf дублируется в object/embed
- Параметр
allowScriptAccess="sameDomain"
- Дублируются размеры ролика
Теперь объект ролика можно получить из window["BridgeMovie"] для IE или document["BridgeMovie"] в остальных браузерах:
function getMovie() {
var M$ = navigator.appName.indexOf("Microsoft")!=-1
return (M$ ? window : document)["BridgeMovie"]
}
Далее мы разберем средства для коммуникации с этим роликом.
Самый древний, знакомый большинству флешеров способ - это вызов javascript-функции посредством getURL с протоколом javascript:
getURL('javascript:функция("параметры");');
- Работает во всех броузерах
- Flash 5 и выше
- Прост в применении
- Не возвращает результат
- Длина передаваемой строки ограничена 508 символами.
Вызов осуществляется так:
fsCommand("функция", "параметры")
Чтобы принять этот вызов, в Javascript должна быть специальная обвязка.
Редактор Macromedia Flash может генерировать ее автоматически при публикации ролика.
Для этого нужно в Publish Settings:
- Во вкладке Formats включить публикацию html-файла
- Во вкладке HTML выбрать Template: Flash with FSCommand
Генерируемый шаблон javascript-обвязки состоит из двух частей: функция обработки и дополнительного кода для IE.
Название функции имеет вид <ИмяРолика>_DoFSCommand . В нашем случае это BridgeMovie_DoFSCommand
Первый аргумент - имя вызываемой функции, второй - строка аргументов.
Простейший вариант выглядит так:
function BridgeMovie_DoFSCommand(command, args) {
// вызвать функцию command с аргументом args
window[command].call(null, args)
}
Вызов, например, функции show из Flash приведет к цепочке вызовов:
- (Flash)
fsCommand("show","something")
- (JS)
BridgeMovie_DoFSCommand("show","something")
- (JS)
show("something")
Этот код нужен только для IE под Windows, в дополнение к BridgeMovie_DoFSCommand , так как в этом браузере fsCommand вызывает не Javascript, а VBScript.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1
&& navigator.userAgent.indexOf("Windows") != -1) {
document.write('<script language=\"VBScript\"\>\n');
document.write('On Error Resume Next\n');
document.write('Sub BridgeMovie_FSCommand(ByVal command, ByVal args)\n');
document.write(' Call BridgeMovie_DoFSCommand(command, args)\n');
document.write('End Sub\n');
document.write('</script\>\n');
}
Здесь VBScript просто передает вызов Javascript'у.
Итак, плюсы и минусы метода fscommand :
- Flash 5 и выше
- Не работает под Mac OS
- Не возвращает результат
- Нужен дополнительный JS-код
Этот способ работает, начиная с Flash 8. В отличие от всех предыдущих способов, он не только вызывает javascript, но и передает обратно возвращаемое значение, по возможности сохраняя его тип.
import flash.external.ExternalInterface;
var result = ExternalInterface.call("func", "param1", "param2", ...);
К сожалению, начиная с Flash 8, где он впервые появился, в ExternalInterface нашли большое количество разнообразных багов. Глюки сериализации, самопроизвольное изменение передаваемых данных и т.п.
Эти ошибки поправлены в новейших версиях Flash Player, но многие продолжают использовать более старые редакции Flash 8,9.
Актуальную информацию об ошибках можно получить из google, набрав "ExternalInterface bug".
- Простота
- Возвращает результат
- Разнообразные баги, в отличие от предыдущих способов
Самый простой способ - установка переменной ролику:
getMovie().SetVariable("message","data")
Обратите внимание - именно SetVariable , не setVariable . Регистр здесь важен.
Чтобы Flash получил значение - можно проверять сообщения, например, на каждом кадре. Это около 12 раз в секунду.
Следующий код срабатывает на каждом кадре и ждет появления значения переменной message .
var message = null
_root.onEnterFrame = function() {
if (message!==null) {
_root.txtRecieve.text = message // получили сообщение
message = null
}
}
- Простота и надежность
- Кросс-браузерность, Flash 5+
- Дорога в одну сторону, не больше одного сообщения за кадр.
Применив ExternalInterface из Flash8+, можно объявить флеш-метод, который будет обрабатывать вызовы из javascript.
Формат вызова:
ExternalInterface.addCallback(функция JS, объект Flash, функция Flash); .
Например, следующий код устанавливает глобальную функцию recieveFromJS как обработчик JS-вызова sendFromJS .
import flash.external.ExternalInterface;
...
ExternalInterface.addCallback("sendFromJS", null, recieveFromJS);
function recieveFromJS(msg) {
_root.txtRecieve.text = msg;
}
В JS достаточно сделать простой вызов:
getMovie().sendFromJS(value);
- Можно тут же получить значение из Flash
- Множество багов в ExternalInterface.
Можно также использовать LocalConnection , как это сделано во Flash-Javascript Integration Kit.
Этот пример пересылает текст из верхнего JS-поля направо во Flash, из нижнего Flash-поля - налево в JS.
Вводите любой, текст и жмите кнопку для пересылки нужным методом.
// Flash Storage example
import flash.external.ExternalInterface;
ExternalInterface.addCallback("sendFromJS", null, recieveFromJS);
function recieveFromJS(msg) {
_root.txtRecieve.text = msg;
}
_root.button.onRelease = function() {
fscommand("recieveFromFlash", _root.txtSend.text);
}
_root.button2.onRelease = function() {
ExternalInterface.call("recieveFromFlash", _root.txtSend.text);
}
_root.button3.onRelease = function() {
var txt = _root.txtSend.text.split('"').join('\\"')
getURL('javascript:recieveFromFlash("'+txt+'");');
}
var message = null
_root.onEnterFrame = function() {
if (message!==null) {
_root.txtRecieve.text = message
message = null
}
}
Скачать .fla - исходник флешки.
function recieveFromFlash(Txt) {
document.getElementById('txtRecieve').value = Txt;
}
function getMovie() {
var M$ = navigator.appName.indexOf("Microsoft")!=-1
return (M$ ? window : document)["BridgeMovie"]
}
function sendSetVariable() {
var value = document.getElementById('txtSend').value
var movie = getMovie()
movie.SetVariable("message", value)
}
function sendExternalInterface() {
var value = document.getElementById('txtSend').value
var movie = getMovie()
movie.sendFromJS(value);
}
/* movie name_DoFSCommand */
function BridgeMovie_DoFSCommand(command, args) {
window[command].call(null, args)
}
// Hook for Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 &&
navigator.userAgent.indexOf("Windows") != -1) {
document.write('<script language=\"VBScript\"\>\n');
document.write('On Error Resume Next\n');
document.write('Sub BridgeMovie_FSCommand(ByVal command, ByVal args)\n');
document.write(' Call BridgeMovie_DoFSCommand(command, args)\n');
document.write('End Sub\n');
document.write('</script\>\n');
}
По просьбам читателей - примеры и исходники вынесены на отдельную страницу.
Успешной интеграции!
|
Thank you for taking the time to publish this information very useful!
리니지 프리서버
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.
리니지 프리서버
Thank you for taking the time to publish this information very useful!
리니지 프리서버
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
리니지 프리서버
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
리니지 프리서버
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
서버모아
Yes i am totally agreed with this article and i just want say that this article is very nice and very informative article.I will make sure to be reading your blog more. You made a good point but I can't help but wonder, what about the other side? !!!!!!THANKS!!!!!!
서버모아
Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include.
서버모아
sudoku 247 is an entertainment website suitable for all ages. Here, in addition to your entertainment, you can also find many other games that serve the purpose of training some skills for children such as Sudoku, Impossible Game, Tetris... Wish you have a good time. relaxing rewarding and fun!
I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.
레플리카사이트
I can see that you are an expert at your field! I am launching a website soon, and your information will be very useful for me.. Thanks for all your help and wishing you all the success in your business.
레플리카사이트
I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before.
명품레플리카
An fascinating discussion is value comment. I think that it is best to write extra on this matter, it won’t be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers
명품레플리카
I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best!
liver hospital in hyderabad
I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best!
https://bit.ly/3un7T6A
I really thank you for the valuable info on this great subject and look forward to more great posts. Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! All the best!
https://bit.ly/3un7T6A
hello!! Very interesting discussion glad that I came across such informative post. Keep up the good work friend. Glad to be part of your net community.
https://bit.ly/3un7T6A
Really good point. your could recognize veb proqramasdirma from here https://atlacademy.az
Whenever you want to have fun go and check our ladies sex in brisbane
Cool site
I've been using WordPress on a number of websites for about a year and am worried about switching to another platform. I have heard good things about keo nhacai. Is there a way I can transfer all my wordpress content into it? Any help would be really appreciated!
I've been using WordPress on a number of websites for about a year and am worried about switching to another platform. I have heard good things about keo nhacai. Is there a way I can transfer all my wordpress content into it? Any help would be really appreciated!
Yes i am completely concurred with this article and i simply need say this article is extremely decent and exceptionally useful article.I will make a point to be perusing your blog more. You made a decent point yet I can"t resist the urge to ponder, shouldn"t something be said about the other side? 토토사이트추천
Thank you so much for the amazing information. I have also check out this site is cycling good for sciatica
I think it's pointless to read such articles anymore. I think now is the time to go one step ahead. I seek progressive writing. When you come to my site, there are many more progressive articles and articles related to 메이저사이트추천 Come to play.
https://mukoff.com/
Last week, deputies were called to a San Marin daycare owned by Goularte's mother regarding an alleged sexual assault involving a child, the Santa Clara County Sheriff's Office said in a statement Wednesday.
https://mukoff.com/
Last week, deputies were called to a San Marin daycare owned by Goularte's mother regarding an alleged sexual assault involving a child, the Santa Clara County Sheriff's Office said in a statement Wednesday.
An intriguing discussion may be worth comment. I’m sure you should write much more about this topic, may well be described as a taboo subject but generally folks are too little to chat on such topics. An additional. Cheers 메이저토토사이트
https://toolbarqueries.google.ki/url?q=https%3A%2F%2Fsite789.com
Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people. play wordle game wordle game
There's no doubt i would fully rate it after i read what is the idea about this article. You did a nice job.. emergency dentist near me
Royalcasino545
betflix เป็นสล็อตออนไลน์ ที่สามารถเล่นเพื่อทำเงินได้ ทางเรามีบริการฝากถอนตลอด 24 ชั่วโมง
biobetgaming ของเราพร้อมให้บริการตลอด 24 ชั่วโมง แชทกับเจ้าหน้าที่เพื่อเริ่มได้เลย คาสิโนออนไลน์ของเรา มีการบริการมากมาย biogaming
เดิมพันออนไลน์กับเว็บเราสิ AMBBET168X ยินดีให้บริการ เราเป็นเว็บตรงจากต่างประเทศจริง เราไม่ได้มาเล่นๆ แต่เราจริงจัง จัดเลย ambbet พร้อมบริการตลอด 24 ชั่วโมง ปลอดภัยไร้กังวล 100%
สล็อตออนไลน์ เรามีพร้อมให้คุณเสร็จสรรพในเว็บเดียว เข้ามาเล่นกับเราได้ที่slotxo168
The assignment submission period was over and I was nervous, and I am very happy to see your post just in time and it was a great help. Thank you ! Leave your blog address below. Please visit me anytime.
How is processing function and additional code for IE done? spin the wheel
How is processing function and additional code for IE done? spin the wheel
It seems like I've never seen an article of a kind like . It literally means the best thorn. It seems to be a fantastic article. It is the best among articles related to 열공캔디 . seems very easy, but it's a difficult kind of article, and it's perfect.
Hello!!! I'm happy to see some great articles on your site. Would you like to come to my site later? My site also has posts, comments and communities similar to yours. Please visit and take a look 카지노사이트
What a post I've been looking for! I'm very happy to finally read this post. 카지노사이트Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.
What a post I've been looking for! I'm very happy to finally read this post. 카지노사이트Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.
While looking for articles on these topics, I came across this article on the site here. As I read your article, I felt like an expert in this field. I have several articles on these topics posted on my site. Could you please visit my homepage? 온라인카지노
reifeladies ist ideal für lokale Kontakte. Jede geile Schlampe auf der Seite hat ihre Fetische und sie hat ihre Begierden.
This is the perfect post.바카라사이트 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.
XDFHDE
I've been troubled for several days with this topic. keo nha cai
, But by chance looking at your post solved my problem! I will leave my blog, so when would you like to visit it?
This is the perfect post.바카라사이트 It helped me a lot. If you have time, I hope you come to my site and share your opinions. Have a nice day.
dfgfd
Which is some inspirational stuff. Never knew that opinions might be this varied. Thank you for all the enthusiasm to provide such helpful information here. 호치민 황제투어
That's a really impressive new idea! 바카라사이트추천 It touched me a lot. I would love to hear your opinion on my site. Please come to the site I run once and leave a comment. Thank you.
jghgfddd
Your blogs definitely stand out to me; the information is engaging and easy to comprehend. I've read a lot of websites, but I still moviedle prefer yours. I enjoyed reading your essay. Now that I've read the essay thoroughly, I have a better quordle comprehension of it. I'd like to read more of your writing in the future.
This is the post I was looking for. I am very happy to read this article. If you have time, please come to my site 카지노사이트 and share your thoughts. Have a nice day.
xdghj
What a nice post! I'm so happy to read this. 온라인카지노사이트 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.
cfhhg
I've been using WordPress on a number of websites for about a year and am worried about switching to another platform. I have heard good things about 카지노사이트추천. Is there a way I can transfer all my wordpress content into it? Any help would be really appreciated!
Like your sharing!
The black screen online helps you relax when using the computer too much.
white screen tools
I was impressed by your writing. Your writing is impressive. I want to write like you.카지노게임사이트 I hope you can read my post and let me know what to modify. My writing is in I would like you to visit my blog.
cfdhh
I was impressed by your writing. Your writing is impressive. I want to write like you.카지노게임추천 I hope you can read my post and let me know what to modify. My writing is in I would like you to visit my blog.
Your writing is perfect and complete. 바카라사이트 However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once?
Your writing is perfect and complete. 바카라사이트 However, I think it will be more wonderful if your post includes additional topics that I am thinking of. I have a lot of posts on my site similar to your topic. Would you like to visit once?
This post gives clear idea designed for the new people of blogging, that truly how to do running a blog. สล็อตโจ๊กเกอร์
I finally found what I was looking for! I'm so happy. 온라인카지노 Your article is what I've been looking for for a long time. I'm happy to find you like this. Could you visit my website if you have time? I'm sure you'll find a post of interest that you'll find interesting.
hjllk
I've been using WordPress on a number of websites for about a year and am worried about switching to another platform. I have heard good things about 바카라사이트. Is there a way I can transfer all my wordpress content into it? Any help would be really appreciated!
There must have been many difficulties in providing this information. 카지노사이트 Nevertheless, thank you for providing such high-quality information.
There must have been many difficulties in providing this information. 카지노사이트 Nevertheless, thank you for providing such high-quality information.
There must have been many difficulties in providing this information. 카지노사이트 Nevertheless, thank you for providing such high-quality information.
There must have been many difficulties in providing this information. 카지노사이트 Nevertheless, thank you for providing such high-quality information.
Your ideas inspired me very much. 온라인바카라사이트 It's amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your opinion. Thank you.
CFBH
SexyPG89 เกม IPRO999 แตกง่าย แตกหนัก แจกจริง
What a post I've been looking for! I'm very happy to finally read this post. 카지노사이트 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.
cfdh
Really no matter if someone doesn't be aware of after that its up to other users that they will help, so here it takes place 온라인카지노사이트.
ghjuyi
What a nice post! I'm so happy to read this. 온라인카지노사이트 What you wrote was very helpful to me. Thank you. Actually, I run a site similar to you. If you have time, could you visit my site? Please leave your comments after reading what I wrote. If you do so, I will actively reflect your opinion. I think it will be a great help to run my site. Have a good day.
gjkl
What a post I've been looking for! I'm very happy to finally read this post. 토토사이트 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.
Отправить комментарий
Приветствуются комментарии:Для остальных вопросов и обсуждений есть форум.