Javascript 在注入脚本中以编程方式获取chrome扩展id

Javascript 在注入脚本中以编程方式获取chrome扩展id,javascript,google-chrome-extension,Javascript,Google Chrome Extension,在我的内容脚本中,我使用这种方法来访问网页的变量: function exec(fn) { var script = document.createElement('script'); script.setAttribute("type", "application/javascript"); script.textContent = '(' + fn + ')();'; document.body.appendChild(script); //run the s

在我的内容脚本中,我使用这种方法来访问网页的变量:

function exec(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')();';
    document.body.appendChild(script); //run the script
    document.body.removeChild(script); //clean up
}

exec( function(){
    var test = websiteVar

    chrome.runtime.sendMessage("extensionID", {test: test}, function(response) {

    });
});
上面写着extensionID,如果我硬编码它,它就会工作。但是,我不能使用
chrome.runtime.id
,因为它被注入到页面中。我想我读到它们在同一个环境下不起作用

有没有办法通过编程方式获取扩展id?

上述示例:

function exec(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')("' + chrome.runtime.id +'")';
    document.body.appendChild(script); //run the script
    document.body.removeChild(script); //clean up
}

exec( function(extensionID){

    var test = websiteVar;
    chrome.runtime.sendMessage(extensionID, {test: test}, function(response) {

    });

});
上述内容的示例:

function exec(fn) {
    var script = document.createElement('script');
    script.setAttribute("type", "application/javascript");
    script.textContent = '(' + fn + ')("' + chrome.runtime.id +'")';
    document.body.appendChild(script); //run the script
    document.body.removeChild(script); //clean up
}

exec( function(extensionID){

    var test = websiteVar;
    chrome.runtime.sendMessage(extensionID, {test: test}, function(response) {

    });

});

在我的回答中:我提供了一个通用的解决方案,可以在向函数传递参数的同时从内容脚本在页面上下文中执行函数。您可以使用它将extensionId作为一个值传递,该值是从
chrome.runtime.id
获得的。是的,只需将其作为一个参数传递即可(“+chrome.runtime.id+”);”chrome.runtime.id获得的。是的,只需将其作为一个参数传递即可(“+chrome.runtime.id+”);”并在函数中使用它。