跳至主要内容

chrome extension can not access in page variable.

http://stackoverflow.com/questions/10527625/google-chrome-extension-script-injections



"name": "Chrome Extension",
"version": "1.0",
"manifest_version": 2,
"content_scripts": [{
    "matches": ["http://pagetoinject/script/into/*"],
    "js": ["contentscript.js"]
}]  
contenscript.js
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
(document.head||document.documentElement).appendChild(s);
s.parentNode.removeChild(s);
also tried this method with no success
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
and I keep getting this error on my javascript console.

so the answer is :
o fix the problem, add script.js to the whitelist, "web_accessible_resources" in yourmanifest file:
{
  "name": "Chrome Extension",
  "version": "1.0",
  "manifest_version": 2,
  "content_scripts": [{
      "matches": ["http://pagetoinject/script/into/*"],
      "js": ["contentscript.js"]
  }],
  "web_accessible_resources": ["script.js"]
}
but i'm not sure the other one says inject by string :
Content scripts are executed in an isolated environment. You have to inject the state method in the page itself.
When you have to want to use one of the chrome.* APIs in the script, you have to implement a special event handler, as described in this answer: Chrome extension - retrieving Gmail's original message.
Otherwise, if you don't have to use chrome.* APIs, I strongly recommend to inject all of your JS code in the page via a dynamic 

Method 1: Inject another file

This is the easiest/best method when you have lots of code. Include your actual JS code in a file, sayscript.js. Then let your content script be as follows (explained here: Google Chome “Application Shortcut” Custom Javascript):
var s = document.createElement('script');
s.src = chrome.extension.getURL("script.js");
s.onload = function() {
    this.parentNode.removeChild(this);
};
(document.head||document.documentElement).appendChild(s);
When your extension's manifest specifies "manifest_version": 2, the injected script.js file has to be added to the "web_accessible_resources" section. For an explanation and example, see this answer.

Method 2: Inject embedded code

This method is useful when you want to quickly run a small piece of code. (See also: How to disable facebook hotkeys with Chrome extension?).
var actualCode = ['/* Code here. Example: */alert(0);',
                  ' // Beware! This array have to be joined',
                  ' // using a newline. Otherwise, missing semicolons',
                  ' //  or single-line comments (//) will mess up your',
                  ' //  code ----->'].join('\n');

var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);

Method 2b: Using a function

For a big chunk of code, quoting the string is not feasible. Instead of using an array, a function can be used, and stringified:
var actualCode = '(' + function() {
    // All code is executed in a local scope.
    // For example, the following does NOT overwrite the global `alert` method
    var alert = null;
    // To overwrite a global variable, prefix `window`:
    window.alert = null;
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
This method works, because the + operator on strings and a function converts all objects to a string. If you intend on using the code more than once, it's wise to create a function to avoid code repetition. An implementation might look like:
function injectScript(func) {
    var actualCode = '(' + func + ')();'
    ...
}
injectScript(function() {
   alert("Injected script");
});
Note: Since the function is serialized, the original scope, and all bound properties are lost!
var scriptToInject = function() {
    console.log(typeof scriptToInject);
};
injectScript(scriptToInject);
// Console output:  "undefined"
inject is ok, of cause you need to active the eval option.

"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",

评论

此博客中的热门博文

My childhood

"Each person's life is like a book; some people prefer to savor it slowly, while others like to gradually forget it. Looking back, I want to see if I can discern the trajectory of the world from my seemingly insignificant life. I am a child from the countryside, and perhaps most people cannot understand what my so-called countryside looks like. Indeed, the impressions of the countryside can be very different depending on the country, and moreover, more than 40 years have passed, during these 40 years of rapid development in China. A phrase suddenly comes to mind, 'I see him building tall buildings, I see him feasting, I see everything collapsing.' The place where I was born is a small town in the southwest of China, a town so small that it only has one street, and the widest part is only 3 meters. Paved with stone slabs, worn by many years of use, the slabs are not flat but rather filled with small bumps and hollows, yet strangely smooth. At the end of the street is a ...

youtube script covid

[INTRO - Soft Music Playing] Narrator: "In August 2020, during the COVID-19 pandemic in China, I experienced a series of events that revealed the overbearing, unreasonable, and ignorant aspects of government policies. This story unfolds my observations and experiences in Xinjiang since April, presented in a neutral and factual manner." [Scene Transition - Music Shifts to a More Reflective Tone] Narrator: "April 8th marked the end of my nearly three-month-long home quarantine in Wuhan, as the lockdown was finally lifted. With Xinjiang gradually reopening since March, my work required me to return there as soon as possible." [Visuals: Scenes of Empty Streets in Wuhan, Transitioning to Busy Airports] Narrator: "My journey back to Xinjiang was fraught with delays. The direct flight on China Southern Airlines kept getting postponed. Reluctantly, I had to transit through Xi'an. Before leaving, I reported my health status to the community in Changji City, where I ...

survilliance in china

  Hello everyone, welcome to my YouTube channel. This is my first video, and I'm very happy to meet you all. I come from China, and looking back, time has passed so quickly. I've been in France for almost 20 years. Sometimes, when I chat with friends, I'm surprised at how little the French know about China. What's even more alarming is that the French media follows the narrative of the Chinese official media. This is why I decided to create a YouTube channel to talk to my French friends about the China I know. Since my parents and friends are still in China, and to avoid unnecessary impact on their lives, I've decided not to appear in person for now. This is how I fulfill my long-standing wish. My first episode is about "Digital Surveillance in China.",  Digital Surveillance: In China, using the official App Store is mandatory. Apple's App Store is China-specific, and all data is stored there. Google's App Store is simply inaccessible in China. If ...