简体   繁体   English

在Chrome扩展程序中加载页面后如何触发Javascript?

[英]How to trigger Javascript after the page loaded in chrome extension?

I have been working on a chrome extension ! 我一直在开发chrome扩展程序! Now my extension takes input from the user and then on click of a button it redirects to a page and fills the data entered in to a specific text field. 现在,我的扩展程序从用户那里获取输入,然后单击按钮,它将重定向到页面并将输入的数据填充到特定的文本字段中。 I am able to redirect to the page but when i try to get the element by using id name it gives null error ! 我能够重定向到页面,但是当我尝试通过使用id名称获取元素时,它给出了null错误! as the javascript is running before the page is getting loaded properly. 因为javascript在页面正确加载之前正在运行。 I tried but could not find a way ! 我尝试了但找不到办法!

In my content script i have this function : 在我的内容脚本中,我具有以下功能:

function redirect(data)
{
location.replace("xyz.html");
        window.onload = function()
        {
            alert();
            var textField = document.getElementById("textField");
            textField.value = data ;
        } 
}

When you call location.replace , you are loading a new page, your current document will be closed which means you content script injected to this document won't work. 调用location.replace ,正在加载新页面,当前文档将关闭,这意味着您注入到该文档的内容脚本将无法工作。

Say you are currently in page A and want to redirect to page B, one workaround would be when you get the data from A, save it to chrome.storage or background page , then when redirected to B, get the data from chrome.storage or persistent page . 假设您当前位于页面A中,并且要重定向到页面B,一种解决方法是,当您从A获取数据时,将其保存到chrome.storage背景页面中 ,然后当您重定向至B时,从chrome.storage获取数据或persistent page

The sample code would look like: 示例代码如下所示:

chrome.storage.local.get("data", function(results) {
    var data = results.data;
    var textField = document.getElementById("textField");
    if (textField) {
        textField.value = data;
    } else {
        chrome.storage.local.set({"data": "your data here"});
        redirect("your data here");
    }
});

function redirect(data) {
    location.replace("xyz.html");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM