2010-12-01 70 views
2

我正在加載主文檔中的網頁的Firefox側邊欄。 現在我想從主文檔調用一個javascript函數來響應側邊欄上的按鈕。 側邊欄如何使主文檔執行其JavaScript函數之一? 到目前爲止,我有一個包含JavaScript代碼的變量,但它如何執行? (在加載網頁的背景?)如何讓邊欄從主文檔執行JavaScript代碼?

回答

7

Dr.Molle對他的回答是正確的,但我總是喜歡工作的例子。

console.log("Opening new page at http://example.com"); 
page = window.open('http://example.com'); 
console.log(page); 
console.log("calling alert on opened page"); 
page.alert("I opened and the previous windows JS called me!!!!"); 
console.log("called alert"); 

示例頁面=> [刪除。請參見下面的更新]

結果:

alert initiated from other page console logs

注: 我只好允許演示代碼的彈出窗口工作但這是另一個問題,SO另一個問題。 ; )

firefox popup blocked notice

UPDATE:

這樣算下來

page.alert() 

工作,因爲它沒有等待網頁加載完成它的工作。爲了能夠調用函數,在加載的頁面上必須確保腳本已經完成加載。爲了說明這一點,我改變了我的例子。

例頁=>http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-call-function-in-opened-page.html

的JS看起來像這樣

page = window.open('http://mikegrace.s3.amazonaws.com/forums/stack-overflow/example-the-other-page.html'); 

var initOtherPage = function() { 
    try { 
    page.showMeTheMoney(); 
    console.log("It worked!"); 
    } catch (e) { 
    console.log("failed to call function on other page because: "+e); 
    setTimeout(function() { 
     console.log("trying again") 
     initOtherPage(); 
    }, 1000); 
    } 
} 
initOtherPage(); 

控制檯輸出

alt text

打開頁

alt text

3

負載使用window.open(網頁),並將其保存到一個變量:

page=window.open('some.htm') 

那麼你可以使用這個變量來訪問窗口內調用函數:

page.someFunction() 
+0

太酷了!我不知道你可以這樣做。 : ) 謝謝! – 2010-12-01 02:14:43

+0

非常感謝! – Nanadada 2010-12-05 10:42:34