-2

我正在嘗試使用內容腳本瀏覽網頁。但是該函數會一直運行,因爲每次頁面發生變化時都會通過腳本運行。我想知道是否有更好的方法來做到這一點,因爲它是一個資源豬,也不允許用戶與頁面交互,因爲不斷刷新。打開窗口並瀏覽頁面

下面是有問題的代碼,很抱歉,如果它看起來很奇怪。我沒有更多的幾個星期瞭解jQuery的知識。

$(document).ready(function(){ 
    console.log("Made it here" + window.location.href); 

    loc = window.location.href; 
    match = loc.match('http://url.com/uc/'); 
    if (match) { 

     window.location = "http://url.com/uc/health/index/1"; 
     console.log("2 here"); 

     window.location = "http://url.com/uc/health/communication/createSelectTemplate"; 

     console.log("3 here"); 
     chrome.storage.local.get('formOption', function(result) { 
      document.getElementById('formTemplate').value = result.formOption; 
      document.forms[0].submit(); 
     }); 

    } 
}); 

的原因,我不得不用,因爲誰使這個網站有超時餅乾值之前,導航三個窗口和網頁無法前一個加載之前被調用。 這是一個內容腳本,所以所有的代碼都在下一頁。也許如果有一種方法來檢查確切的網址?但是當我一直在玩這個計算機時沒有區分。

urlhere.com/uc/ 

urlhere.com/uc/health/index/1 
+2

你爲什麼$(文件)。就緒裏面的$(document).read? –

+4

'window.location'會加載新的網頁,新的內容和所有下一個代碼不會工作 –

+0

我試圖等待每個頁面準備好。但看着它它什麼都不做,所以我將它們刪除。 –

回答

2

每次導航(如分配window.location之後),你的腳本停止執行卸載與頁面,並在接下來的頁面加載,內容腳本確實裝再次。如果加載了相同的腳本,並且與相同的初始狀態,它當然會執行相同的操作。

可能的解決方案(有很多):

  1. 與您匹配(=更好的通知實際上是不斷變化的狀態),更精確。

    loc.match('http://url.com/uc/')只會檢查地址是否包含該字符串 - 顯示的所有網址都會顯示。爲什麼不使用loc == 'http://url.com/uc/'(並檢查中間頁面)?

  2. 使用細粒度的內容腳本(=加載不同的腳本)。

    Manifest定義哪些頁面獲取加載的腳本。我假設你有這樣的事情:

    "content_scripts" : [{ 
        "js" : ["jquery.js", "content1.js"], 
        "matches": ["http://*"] 
    }] 
    

    你可以製作幾個腳本,讓Chrome解析URL。例如,content1.js會做第一次重定向,content2.js會做第二次。

    "content_scripts" : [{ 
        "js" : ["jquery.js", "content1.js"], 
        "matches": ["http://url.com/uc/"] 
    }, { 
        "js" : ["jquery.js", "content2.js"], 
        "matches": ["http://url.com/uc/health/index/1"] 
    }] 
    
  3. 使用一些持續狀態(導航之間的持續),以表明其重定向階段是你(=控制變化狀態自己)。

    頁的sessionStorage非常適合這個,因爲它是唯一持久的標籤內:

    if (match) { 
        switch (sessionStorage.redirectStage) { 
        case 3: 
         // We're at the final page, do actual work 
         break; 
        case 2: 
         sessionStorage.redirectStage = 3; 
         window.location = "http://url.com/uc/health/communication/createSelectTemplate"; 
         break; 
        default: // Includes initial state when it's unset 
         window.location = "http://url.com/uc/health/index/1"; 
        } 
    } 
    
+0

你是一個拯救生命的人,並給了很多很好的信息!非常感謝。 –

+0

你認爲你的第三個答案會比第一個更好嗎? –