- Code: Select all
void MyApp::OnContextCreated(
CefRefPtr<CefBrowser> browser,
CefRefPtr<CefFrame> frame,
CefRefPtr<CefV8Context> context) {
CefRefPtr<CefV8Value> global = context->GetGlobal();
CefRefPtr<CefV8Value> myCoolGlobal = CefV8Value::CreateObject(NULL);
myCoolGlobal->SetValue("readFile",
CefV8Value::CreateFunction("readFile", new ReadFile()),
V8_PROPERTY_ATTRIBUTE_READONLY);
global->SetValue("myCoolGlobal", myCoolGlobal, V8_PROPERTY_ATTRIBUTE_READONLY);
}
ReadFile is a V8Handler which spawns a new thread which reads a file, then posts a task to the renderer thread to execute the callback. Shown below.
- Code: Select all
class ReadFile: public CefV8Handler {
public:
virtual bool Execute(
const CefString& name,
CefRefPtr<CefV8Value> object,
const CefV8ValueList& arguments,
CefRefPtr<CefV8Value>& retval,
CefString& exception) {
std::thread t(std::bind(&ReadFile::DoReadFile, this, CefV8Context::GetCurrentContext(), arguments[0]));
t.detach();
return true;
}
void DoReadFile(CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Value> callback) {
std::string message = GetFileContents("/home/jonathan/test.txt");
CefPostTask(
TID_RENDERER,
CefCreateClosureTask(base::Bind(&ReadFile::DoCallback, this, context, callback, message))
);
}
void DoCallback(CefRefPtr<CefV8Context> context, CefRefPtr<CefV8Value> callback, std::string message) {
CefV8ValueList args;
args.push_back(CefV8Value::CreateString(message));
callback->ExecuteFunctionWithContext(context, NULL, args);
}
std::string GetFileContents(const char *filename) {
std::ifstream ifs("/home/jonathan/cef/build/cefsimple/Debug/test.txt", std::ios::in);
if(!ifs.is_open()) {
return "No File";
}
std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
return str;
}
private:
IMPLEMENT_REFCOUNTING(ReadFile)
};
My JavaScript looks like this
- Code: Select all
myCoolGlobal.readFile(
function(message) {
console.log(message);
}
);
No matter what I do, ifs.is_open() always returns false. I've tried fopen, and even CefStreamReader::CreateForFile(), but non of these file io calls ever find my file.
I've tried changing ownership and permissions of my file. It's as if I can't read any files from the file system and I have no idea why.