一旦你完成了PPAPI插件的開發,實際使用時可能會有下列需求:
- 動态建立PPAPI插件
- 删除PPAPI插件
- 改變PPAPI插件的尺寸
實作起來很簡單,從JS裡直接通路DOM(BOM)即可。下面是一個示例HTML檔案:
<!DOCTYPE html>
<html>
<!--
Copyright (c) 2016 [email protected]微信訂閱号“程式視界”(programmer_sight).
All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->
<head>
<style type="text/css">
#pluginContainer
{
padding: 0px;
width: 1220px;
height: 540px;
background-color: gray;
}
</style>
<script type="text/javascript">
function createPlugin() {
var plugin = document.createElement("embed");
plugin.setAttribute("id", "explugin");
plugin.setAttribute("type", "application/x-ppapi-example");
plugin.setAttribute("width", "1200px");
plugin.setAttribute("height", "520px");
var container = document.getElementById("pluginContainer");
container.appendChild(plugin);
}
function deletePlugin(){
var container = document.getElementById("pluginContainer");
var plugins = container.getElementsByTagName("embed");
if(plugins.length >= 1){
container.removeChild(plugins[0]);
}
}
function changeSize() {
var plugin = document.getElementById("examplePlugin");
plugin.setAttribute("width", "600px");
plugin.setAttribute("height", "300px");
}
function restoreSize() {
var plugin = document.getElementById("examplePlugin");
plugin.setAttribute("width", "1200px");
plugin.setAttribute("height", "520px");
}
</script>
<meta charset="UTF-8">
<title>Plugin Test</title>
</head>
<body>
<input type="button" value="CreatePPAPI" onclick="createPlugin()"/>
<input type="button" value="ChangeSize" onclick="changeSize()"/>
<input type="button" value="RestoreSize" onclick="restoreSize()"/>
<input type="button" value="DeletePPAPI" onclick="deletePlugin()"/>
<div id="pluginContainer">
<!--
<embed id="examplePlugin" type="application/x-ppapi-example" width="1200px" height="520px" />
-->
</div>
</body>
</html>
上面的HTML示範了建立、删除、改變大小幾種常見的操作。
需要注意的是,當你删除一個PPAPI插件時,會調用到PPP_Instance的DidDestroy方法,你需要在這裡的C++/C代碼裡删除插件執行個體,釋放相應的資源,比如Graphics 2D,Image Data等。DidDestroy調用後,過一會兒,如果沒有其他的插件執行個體存在,就會接着調用PPP_ShutdownModule;如果有,則不會。個中邏輯,可以參考了解PPAPI的設計。
當你設定embed元素的width和height屬性後,PPAPI插件裡,PPP_Instance的DidChangeView方法會被調用,你需要在這裡根據新尺寸重新建立相關資源。
就這樣吧。
其他參考文章詳見我的專欄:【CEF與PPAPI開發】。