首页 > 解决方案 > Chrome 扩展将变量传递给在“document.start”上运行的脚本

问题描述

在我的 manifest.json 我有

"content_scripts": [
    {
      "matches": [ "https://*/*", "http://*/*" ],
      "run_at": "document_start",
      "all_frames": true,
      "match_about_blank": true,
      "js": [ "run_on_every_page.js" ]
    }

在 run_on_every_page.js

var yourCustomJavaScriptCode = 'document.pageVariable={I_want_variable_from background.js_to_be_inserted_here};';
var script = document.createElement('script');
var code = document.createTextNode('(function() {' + yourCustomJavaScriptCode+ '})();');
script.appendChild(code);
document.documentElement.appendChild(script);

如何将变量从 background.js 插入到“I_want_variable_from background.js_to_be_inserted_here”?

Background.js 是:

var myVariable=Math.random();//Dynamic variable that changes based on user activity

标签: google-chrome-extension

解决方案


推荐阅读