2016-12-22 90 views
0

我試圖從天氣網站添加外部網絡小部件。它給了我somethink這樣的:將外部網絡小部件添加到面板

<div id='cont_5caab8f298a3d34d53973f2d8906d1f7'><script type='text/javascript' async src='https://www.tiempo.com/wid_loader/5caab8f298a3d34d53973f2d8906d1f7'></script></div> 

我試圖創建與代碼HTML控件並將其添加到我的面板,但它並不顯示。

回答

1

您提供的嵌入代碼僅在包含在HTML文件中時纔有效。動態添加時不起作用。例如,如果你在Web瀏覽器中打開一個空的HTML文件,然後運行:

document.body.innerHTML += "<div id='cont_5caab8f298a3d34d53973f2d8906d1f7'><script type='text/javascript' async src='https://www.tiempo.com/wid_loader/5caab8f298a3d34d53973f2d8906d1f7'></script></div>"; 
在開發商(F12)控制檯

,你會看到,外部內容不會被加載。這是因爲以這種方式添加時,腳本will not會自動執行。

但是,您不需要執行此外部腳本。它所做的只是創建並插入一個iframe,並設置一些屬性和樣式。如果我們看一下script的源代碼,我們可以將它翻譯成GWT等價物。

嵌入JS腳本:

conte = document.getElementById("cont_5caab8f298a3d34d53973f2d8906d1f7"); 
        if (conte) { 
         conte.style.cssText = "width: 176px; color: #868686; background-color:#FFFFFF; border:1px solid #D6D6D6; margin: 0 auto; font-family: Roboto;"; 
         elem = document.createElement("iframe"); 
         elem.style.cssText = "width:176px; color:#868686; height:200px;"; 
         elem.id = "5caab8f298a3d34d53973f2d8906d1f7"; 
         elem.src = "https://www.tiempo.com/getwid/5caab8f298a3d34d53973f2d8906d1f7"; 
         elem.frameBorder = 0; 
         elem.allowTransparency = true; 
         elem.scrolling = "no"; 
         elem.name = "flipe"; 
         conte.appendChild(elem); 
        } 

GWT等價的:

public class Hello implements EntryPoint { 
    public void onModuleLoad() { 
     Panel root = RootPanel.get("main"); // replace with your Panel 

     //This doesn't work: 
     //HTML embed = new HTML("<div id='cont_5caab8f298a3d34d53973f2d8906d1f7'><script type='text/javascript' async src='https://www.tiempo.com/wid_loader/5caab8f298a3d34d53973f2d8906d1f7'></script></div>"); 

     //This does: 
     Frame embed = new Frame("https://www.tiempo.com/getwid/5caab8f298a3d34d53973f2d8906d1f7"); 
     embed.setStyleName(""); // remove GWT styling. You could add your own CSS class here. 
     embed.getElement().setAttribute("style", "width:176px; color:#868686; height:200px;"); 
     embed.getElement().setAttribute("frameborder", "0"); 
     embed.getElement().setAttribute("scrolling", "no"); 

     root.add(embed); 
    } 
} 
+0

Thx,完美無瑕! – jpp1jpp1

0

您可以使用IFrame元素來加載外部內容。

final Frame frame = new Frame("url"); 
frame.addLoadHandler(new LoadHandler() { 
    @Override 
    public void onLoad(LoadEvent event) { 
     // do stuff here 
    } 
}); 
RootPanel.get("mydiv").add(frame); 

但請注意,由於跨站點腳本,您將無法與外部內容進行交互。

+0

我已經嘗試過框架,它與一個單一的URL,但不適合我的情況。 \t \t HTMLPanel weather = new HTMLPanel(「

」); \t \t weather.setSize(「300px」,「125px」); \t \t body.add(weather); – jpp1jpp1